To raise an exception means to signal that the program cannot proceed normally due to an error or other condition. (In other programming languages, such as Java, the equivalent term is to throw an exception.)
Two values accompany the raising of an exception: the
type and the value. For example, if a program
attempts to open an existing disk file but there is no
such file, the type is
IOError, and the
value is an instance of the
class that contains additional information about this
For more information about raising exceptions, see
Section 23.6, “The
raise statement: Cause an
A program may choose to handle an exception. That is, a program may say that if a certain exception or category of exceptions occurs in a specific block of code, Python must execute another code block called a handler.
A traceback is a message from Python showing where an exception occurred.
If you type a statement in conversational mode that causes an exception, you will see a short traceback like this:
>>> x = 59 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
The above example showed that the offending statement was
read from the standard input stream (
When looking at a traceback, always look at the last line
first. It tells you the general type of exception (in the
ZeroDivisionError), followed by
additional details (“integer division or modulo by
If an exception occurs inside one or more function calls, the traceback will give a complete list of the functions involved, from outermost to innermost. Again, the last line shows the exception type and details.
>>> def f(): g() ... >>> def g(): h() ... >>> def h(): return 1/0 ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in f File "<stdin>", line 1, in g File "<stdin>", line 1, in h ZeroDivisionError: integer division or modulo by zero