Exception Propagation
When an exception is raised, the
exception-propagation mechanism takes control. The normal control
flow of the program stops, and Python looks for a suitable exception
handler. Python’s try
statement
establishes exception handlers via its except
clauses. The handlers deal with exceptions raised in the body of the
try
clause, as well as exceptions that propagate
from any of the functions called by that code, directly or
indirectly. If an exception is raised within a try
clause that has an applicable except
handler, the
try
clause terminates and the handler executes.
When the handler finishes, execution continues with the statement
after the try
statement.
If the statement raising the exception is not within a
try
clause that has an applicable handler, the
function containing the statement terminates, and the exception
propagates upward to the statement that called the function. If the
call to the terminated function is within a try
clause that has an applicable handler, that try
clause terminates, and the handler executes. Otherwise, the function
containing the call terminates, and the propagation process repeats,
unwinding the stack of function calls until an applicable handler is
found.
If Python cannot find such a handler, by
default the program prints an error message to the standard error
stream (the file sys.stderr
). The error message includes a traceback that gives details about functions terminated during propagation. You can change Python’s default ...
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.