OUTDATED, DO NOT USE: This tutorial was written in 1999 and was based on Python 1.5.2, which today is a really old version. I would not recommend using this tutorial to learn modern Python as the language has changed significantly. This page is left here in it's mostly-original form for historic reference only. Please consult the Python website for current documentation.

The try/except statements

Python supports a fully refined exception handling mechanism, similar to the new C++ try block. When Python encounters an error, it raises an exception. Normally this results in the program being terminated with a stack trace being printed. However you can take advantage of exception handling for your own purposes, or as just a simple way to ignore errors.

  • Code for which you want to trap errors should be wrapped in a try block, as
    try:
       print 5 / 0  # division by zero
    except:
       pass  # simply ignore it
    
  • You can specify a partcular type of error to be handled by naming it after the except keyword. All other errors are left unhandled.
    try:
       print 5 / 0  # division by zero
    except ZeroDivisionError:
       pass  # simply ignore it
    
  • You can specify more than one except clause, and more than one type of error for each clause by using a tuple.
    try:
       dosomething()
    except MemoryError:
       print 'out of memory'
    except (AssertionError, KeyboardInterrupt):
       print 'program aborted'
    
  • You can also provide an else clause, which gets run only if no exceptions occurred.
    try:
       dosomething()
    except:
       print 'an error occured'
    else:
       print 'succeeded'
    
  • Some exceptions may carry extra data along with them. This extra data can be any arbitrary object, but are usually just strings which contain a human readble explanation. To get this extra data, use an except clause with an extra argument.
    try:
       print array[40]
    except IndexError, extradata:
       print 'Indexing error:', extradata
    
  • There is another form of the try statement which is useful when you always need to perform a cleanup operation regardless if an operation succeeded or not. This form can not contain any except or else blocks, and is written as
    file = open("somefile.txt","rw")   # open a file
    try:
       dosomething( file )
    finally:
       file.close()    # always close it even if try block failed
    

Nesting of exception handlers

  • Try blocks may be nested. They are "unwrapped" in the same order in which they were encountered at run time.
  • The first except clause which matches the raised exception is executed. If a given try block does not catch the exception, it is bubbled up to the next enclosing try block. If the exception bubbles up all the way to the top and is not caught, Python will invoke its own stack-dump handler.
  • When bubbling up, all finally blocks are executed in order. However, any code which may have been after the try block will be skipped.

Raising your own exceptions

  • The simplest exception to raise is an assertion failure. Just use the assert statement
    try:
       assert size != 0, "size is zero somehow"
    
    except AssertionError, reason:
       print 'Help! ', reason
    
  • Other arbitrary exceptions may be created with the raise statement
    MyError = "my application error"  #declare an error type
    
    def myfunc():
       raise MyError
    
    try:
       myfunc()
    except MyError:
       print 'Huh, an error occured.'
    
  • You can pass in extra information as any data type you want by adding an extra argument to the raise statement.
    raise MyError, CurrentStateList
    
  • Exceptions match by the identity (a is b) of the error string, not by the equality (a == b) of the strings. Look at the following example,
    MyError1 = "an error"
    MyError2 = "an error"
    
    try:
       raise MyError2
    except MyError1:
       print "error 1"
    except MyError2:
       print "error 2"  --> this handler is executed