Previous | Next


You might experience the traceback error message whenever something goes wrong with your code. If you are not, try with the following example which we divide a value with zero.

>>> def test():
  1/0
 
>>> test()

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    test()
  File "<pyshell#23>", line 2, in test
    1/0
ZeroDivisionError: integer division or modulo by zero
The traceback is Python’s way of telling you that something unexpected has occurred during runtime. In the Python world, runtime errors are called exceptions. We should know how to handle the exceptions so that we can spot what’s the error and then recover it rather than letting the program terminates or crashes unexpectedly. The try/except statement in Python will help you on this. The general form of the try/except statement looks like this:
try:
  #your code (which might cause a runtime error)
except:
  #your error-recovery code
finally:
  #your housekeeping code

Let’s try to divide a value with zero in try/except statement.

>>> def test():
  try:
    1/0
  except:
    print 'error!'
   
>>> test()
error!
Notice that, the program doesn’t raise a traceback error message, instead, it print a pre-defined error message.

Be specific with your exceptions:

Except is great in catching of all the errors. Sometimes, you may want to catch the actual error so that you know how and what to recover when it happen. Take a look if the following example.
>>> def test():
  try:
    1/0
  except ZeroDivisionError:
    print 'Can\'t divide by zero!'
   
>>> test()
error!
The following table describes some of the most important built-in exception classes.
Class Name Description
Exception The base class for all exceptions
AttributeError Raised when attribute reference or assignment fails
Exception The base class for all exceptions
IOError Raised when trying to open a nonexistent file (among other things)
IndexError Raised when using a nonexistent index on a sequence
KeyError Raised when using a nonexistent key on a mapping
NameError Raised when a name (variable) is not found
SyntaxError Raised when the code is ill-formed
TypeError Raised when a built-in operation or function is applied to an object of the wrong type
ValueError Raised when a built-in operation or function is applied to an object with the correct type, but with an inappropriate value
ZeroDivisionError Raised when the second argument of a division or modulo operation is zero

More Than One except Clause:

The try/except statement allow you to catch more than one exception. The following example show you how you can do that in Python. Let’s modify the previous example so that test() function will take two arguments.
>>> def test(val1, val2):
  try:
    val1/val2
  except ZeroDivisionError:
    print 'Can\'t divide by zero!'
  except TypeError:
    print 'Incorrect type of argument!'
  except:
    print 'Other error!'
Notice that we catch more than one exception in the function. A ZeroDivisionError, TypeError and exception. Let’s call the function with division of zero.
>>> test(1,0)
Can't divide by zero!
Let’s call the function with passing invalid type of argument.
>>> test('abc', 8)
Incorrect type of argument!

Catching two or more Exceptions with One Block:

Python allow you to catch more than 1 exception in the same block. Let’s modify the test() function again so that it group both ZeroDivisionError and TypeError in the same block.
>>> def test(val1, val2):
  try:
    val1/val2
  except (ZeroDivisionError, TypeError):
    print 'Invalid type or can\'t divide by zero!'
  except:
    print 'Other error!'
Let’s call the function now.
>>> test(1,0)
Invalid type or can't divide by zero!
>>> test('abc', 8)
Invalid type or can't divide by zero!

Error log:

Often, you may create a program with logging enable so that it write the log to a file when there is an error in the program. The following is a sample program that prints out the exception.
>>> def test():
  try:
    1/0
  except Exception, e:
    print 'Error: ' + str(e)
Notice that we cast e to string, this is because e is an object rather than a string. Try to call test() and it print the error message.
>>> test()
Error: integer division or modulo by zero

Finally:

The finally clause is used to do housekeeping after a possible exception. The finally clause will be executed, no matter what exceptions occur in the try clause.
>>> def test():
  try:
    1/0
  except Exception, e:
    print 'Error: ' + str(e)
  finally:
    print 'Remember: Do not divide value by zero!'
Try to call test() and it printed two messages. one from except clause, another from finally clause.
>>> test()
Error: integer division or modulo by zero
Remember: Do not divide value by zero!

Previous | Next