Recall
Some key points in this chapter:
- Raising an exception happens when something goes wrong. We looked at division by zero as an example. Exceptions can also be raised with the
raise
statement. - The effects of an exception are to interrupt the normal sequential execution of statements. It saves us from having to write a lot of
if
statements to check to see if things can possibly work or check to see if something actually failed. - Handling exceptions is done with the
try:
statement, which has anexcept:
clause for each kind of exception we want to handle. - The exception hierarchy follows object-oriented design patterns to define
a number of subclasses of the
Exception
class we can work with. Some additional exceptions,SystemExit
andKeyboardInterrupt
, are not subclasses of theException
class; handling these introduces risks and doesn’t solve very many problems, so we generally ignore them. - Defining our own exceptions is a matter of extending the
Exception
class. This makes it possible to define exceptions with very specific semantics.
Synopsis
In this chapter, we went into the gritty details of raising, handling, defining, and manipulating exceptions. Exceptions are a powerful way to communicate unusual circumstances or error conditions without requiring a calling function to explicitly check return values. There are many built-in exceptions and raising them is trivially easy. There are several different syntaxes for handling different exception events.
Get hands-on with 1400+ tech skills courses.