9

i want to write a function to report the different results from another function there are some exceptions among these results but I cannot convert them into if statement

example :

if f(x) raise a ValueError, then my function has to return a string 'Value' if f(x) raise a TypeError, then my function has to return a string 'Type

But I don't know how to do this in Python. Can someone help me out.

My Code is like this: -

def reporter(f,x):    

    if f(x) is ValueError():
        return 'Value'
    elif f(x) is E2OddException():
        return  'E2Odd'
    elif f(x) is E2Exception("New Yorker"):
        return 'E2'
    elif f(x) is None:
        return 'no problem'
    else:
        return 'generic'
2
  • 3
    WHY ARE YOU SHOUTING? ..... Seriously, please don't use all-caps. It's hard to read and makes our (mental) ears hurt. Commented Jan 25, 2013 at 6:58
  • I'm so so sorry about that..I'm just getting crazy about that. My homework will due tomorrow actually. Commented Jan 25, 2013 at 7:02

4 Answers 4

18

You have try-except to handle exceptions in Python: -

def reporter(f,x): 
    try:
        if f(x):  
            # f(x) is not None and not throw any exception. Your last case
            return "Generic"
        # f(x) is `None`
        return "No Problem"
    except ValueError:
        return 'Value'
    except TypeError:
        return 'Type'
    except E2OddException:
        return 'E2Odd'
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! But I have not learned about this in my course. So maybe I cannot use it.
@user2010023 try-except is the only way to handle exceptions.
2
def reporter(f,x):    
    try:
        if f(x) is None:
            return 'no problem'
        else:
            return 'generic'
    except ValueError:
        return 'Value'
    except E2OddException:
        return  'E2Odd'
    except E2Exception:
        return 'E2'

Comments

0

You put your function call in a try-except construct like

try:
    f(x)
except ValueError as e:
    return "Value"
except E20ddException as e:
    return "E20dd"

The function itself does not return the exception, the exception is caught outside.

Comments

-2
def reporter(f,x):    
    try:
        if f(x) is None:
            return 'no problem'
        else:
            return 'generic'
    except ValueError:
        return 'Value'
    except E2OddException:
        return  'E2Odd'
    except E2Exception:
        return 'E2'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.