-
The raising of an exception interrupts normal program flow and transfers control to an exception handler.
-
Exception handlers are defined using the try … except construct.
-
The try blocks define a context in which exceptions can be detected.
-
Corresponding the except blocks define handlers for specific types of exceptions.
-
Python uses exceptions pervasively and many built-in language features depend on them.
-
The except blocks can capture an exception object, which is often of a standard type such as ValueError, KeyError or IndexError.
-
Programmer errors such as IndentationError and SyntaxError should not normally be handled.
-
Exceptional conditions can be signaled using the raise keyword which accepts a single parameter of an exception object.
-
Raise without an argument within an except block re-raises the exception which is currently being processed.
-
We tend not to routinely check for TypeErrors. To do so would negate the flexibility afforded to us by Python's dynamic type system.
-
The exception objects can be converted to strings using the str() constructor for the purposes of printing message payloads.
-
The exceptions thrown by a function form part of it's API and should be appropriately documented.
-
When raising exceptions prefer to use the most appropriate built-in exception type.
-
Clean-up and restorative actions can be performed using the try … finally construct which may optionally be used in conjunction with except blocks.
Along the way we saw that:
-
The output of the print() function can be redirected to stderr using the optional file argument.
-
Python supports the logical operators and and or for combining boolean expressions.
-
Return codes are too easily ignored.
-
Platform specific actions can be implemented using an Easier to Ask Forgiveness than Permission approach facilitated by intercepting ImportErrors and providing alternative implementations.