To raise an exception, you use the raise statement with an argument that is either a class (which should subclass Exception for the "catch clause") or an instance.
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in ?
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
Exception: hyperdrive overload
2)custom Exception class
be sure to subclass Exception (either directly or indirectly, which means that subclassing any other built-in exception is okay). Thus, writing a custom exception basically amounts to something like this:
class SomeCustomException(Exception): pass
3) catch exception
1 more than one except clause
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except ZeroDivisionError:
print "The second number can't be zero!"
except TypeError:
print "That wasn't a number, was it?"
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except (ZeroDivisionError, TypeError, NameError):
print 'Your numbers were bogus...'
3 catch the object
If you want access to the exception object itself in an except clause, you can use two arguments instead of one. (Note that even when you are catching multiple exceptions, you are supplying except with only one argument—a tuple.) Because you explicitly catch the object itself, you can print it out so the user can see what happened.
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except (ZeroDivisionError, TypeError), e:
print e
4) catch all vs catch most
If you do want to catch all exceptions in a piece of code, you can simply omit the exception class from the except clause:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print x/y
except:
print 'Something wrong happened...'
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = x/y
print 'x/y is', value
except Exception, e:
print 'Invalid input:', e
5) "else" and "finally" statement
In some cases, it can be useful to have a block of code that is executed unless something bad happens; as with conditionals and loops, you can add an else clause to the try/except statement:
while True:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = x/y
print 'x/y is', value
except:
print 'Invalid input. Please try again.'
else:
break
Finally, there is the finally clause.
the finally clause will be executed, no matter what exceptions occur in the try clause
. You can use it to do housekeeping after a possible exception. It is combined with a try clause:
x = None
try:
x = 1/0
finally:
print 'Cleaning up...'
del x