Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, distinguishing custom exceptions

fairly new to Python here. Have this code:

def someFunction( num ):
    if num < 0:
        raise Exception("Negative Number!")
    elif num > 1000:
        raise Exception("Big Number!")
    else:
        print "Tests passed"


try:
    someFunction(10000)
except Exception:
    print "This was a negative number but we didn't crash"
except Exception:
    print "This was a big number but we didn't crash"
else:
    print "All tests passed and we didn't crash"

I originally used raise "Negative Number!" etc but quickly discovered that this was the old way of doing things and you have to call the Exception class. Now it's working fine but how do I distinguish between my two exceptions? For the code below it's printing "This was a negative number but we didn't crash". Any pointers on this would be great. Thanks!

like image 719
Kex Avatar asked Sep 11 '15 12:09

Kex


1 Answers

you need to create your own exception classes if you want to be able to distinguish the kind of exception that happened. example (i inherited from ValueError as i think this is the closest to what you want - it also allows you to just catch ValueError should the distinction not matter):

class NegativeError(ValueError):
    pass

class BigNumberError(ValueError):
    pass

def someFunction( num ):
    if num < 0:
        raise NegativeError("Negative Number!")
    elif num > 1000:
        raise BigNumberError("Big Number!")
    else:
        print "Tests passed"

try:
    someFunction(10000)
except NegativeError as e:
    print "This was a negative number but we didn't crash"
    print e
except BigNumberError as e:
    print "This was a big number but we didn't crash"
    print e
else:
    print "All tests passed and we didn't crash"
like image 103
hiro protagonist Avatar answered Oct 02 '22 11:10

hiro protagonist