Leveraging exception matching rules
The try
statement lets us capture an exception. When an exception is raised, we have a number of choices for handling it:
- Ignore it: If we do nothing, the program stops. We can do this in two ways—don't use a
try
statement in the first place, or don't have a matchingexcept
clause in thetry
statement. - Log it: We can write a message and use a
raise
statement to let the exception propagate after writing to a log; generally, this will stop the program. - Recover from it: We can write an
except
clause to do some recovery action to undo any effects of the partially completedtry
clause. - Silence it: If we do nothing (that is, use the
pass
statement), then processing is resumed after thetry
statement. This silences the exception. - Rewrite it: We can raise a different exception. The original exception becomes a context for the newly raised exception.
What about nested contexts? In this case...