Next / Previous / Contents / TCC Help System / NM Tech homepage

25.2. Life cycle of an exception

If you anticipate that executing a particular statement may cause an exception and you don't want your program to terminate and display a traceback, you can use a try construct to specify handlers to be executed if an exception occurs. For details, see Section 23.8, “The try statement: Anticipate exceptions”.

If an exception occurs inside a function and it is not handled at that level by a try construct, Python will work back through the pending function calls until it either finds a handler for that exception or runs out of pending function calls.

If there are multiple handlers for the exception in calling functions, the innermost will be used. If there are no handlers for the exception in calling functions, you will get a stack traceback and the program will terminate.

>>> def f():
...     try:
...         g()
...     except ValueError, detail:
...         print "Caught a ValueError:", detail.message
... 
>>> def g(): h()
... 
>>> def h():
...     raise ValueError('This is a test.')
... 
>>> f()
Caught a ValueError: This is a test.

In the example above, function f() calls function g(), which in turn calls function h(). Function h() raises a ValueError exception, but there is no try: block around it. Python looks to see if there is a ValueError handler in g(), but there is not. Finally a handler for ValueError is found inside function f(), so control resumes inside that handler. Note that no stack traceback is displayed, because the ValueError exception was handled successfully.