Top  | Previous | Next

Exception Handling

Exception handling is a language feature of many high-level languages that allows you to "catch" a runtime error and deal with it as you see fit. On the flip side, it allows you to "raise" or "throw" an error in your code, which will break out of whatever code is currently executing and jump to the nearest enclosing catch block that knows how to handle your error.

 

For example, dividing by zero raises a ZeroDivisionError. You can catch this error using a try...except block, like this:

try:

   result = 8 / 0

   print "this will never get called"

except ZeroDivisionError:

   print "oops - can't divide by zero"

 

You don't have to specify a particular type of error to catch - you can use the except keyword by itself to catch any kind of exception. You can also assign the details of the exception to a tuple of variables, which you can use in your error reporting. You can also have multiple except blocks for one try block, each that handle different kinds of exceptions. This example shows these variations:

 

def someDangerousFunction():

   raise IOError(42,"oh no")

try:

   someDangerousFunction()

except IOError, (errno, description):

   print "An I/O error occurred: "+description

except:

   print "An unexpected error occurred"

 

You can learn more about exceptions at https://docs.python.org/2/tutorial/errors.html#handling-exceptions.