Exception Handling
When errors occur, Python throws an exception and prints an informative traceback to standard output. If the error occurred in a source file and not a console session, you get the filename and line number. Here’s a simple error, nested three functions deep, and its traceback:
>>> def func1(arg): ... func2(arg) ... >>> def func2(arg): ... func3(arg) ... >>> def func3(arg): ... # this should cause an error ... return arg / 0 ... >>> func1(17) Traceback (innermost last): File "<interactive input>", line 0, in ? File "<interactive input>", line 2, in func1 File "<interactive input>", line 2, in func2 File "<interactive input>", line 3, in func3 ZeroDivisionError: integer division or modulo >>>
The traceback tells us where the error happened and the enclosing functions that called the functions that caused the error.
Exceptions can be handled using the
try
...except and
try
...finally
structure. If you aren’t used to exception handling, these
offer two benefits over Visual
Basic-style error-handling. First, you can write a decent-sized chunk
of code and put the error handlers at the end; the intent of the
programmer is clearer than with a lot of on
error
goto and
on
error
resume
next statements. Second,
exception handlers don’t work on just the present chunk of
code, but also on any subroutines within it, however deeply nested.
The
except
clause can optionally specify
particular error types to look for or handle all errors:
>>> try: ... y_scale_factor = plotHeight / (dataMax ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access