Test Your Knowledge: Answers

 

 
  1. Exception processing is useful for error handling, termination actions, and event notification. It can also simplify the handling of special cases and can be used to implement alternative control flows. In general, exception processing also cuts down on the amount of error-checking code your program may require—because all errors filter up to handlers, you may not need to test the outcome of every operation.
  2. Any uncaught exception eventually filters up to the default exception handler Python provides at the top of your program. This handler prints the familiar error message and shuts down your program.
  3. If you don’t want the default message and shutdown, you can code try/except statements to catch and recover from exceptions that are raised. Once an exception is caught, the exception is terminated and your program continues.
  4. The raise and assert statements can be used to trigger an exception, exactly as if it had been raised by Python itself. In principle, you can also raise an exception by making a programming mistake, but that’s not usually an explicit goal!
  5. The try/finally statement can be used to ensure actions are run after a block of code exits, regardless of whether it raises an exception or not. The with/as statement can also be used to ensure termination actions are run, but only when processing object types that support it.