Handling exceptions

Exceptions that arise in a context manager's block will be passed to the __exit__() method of the context manager. The standard bits of an exception – the class, arguments, and the traceback stack – will all be provided as argument values.

The __exit__() method can do one of the following two things with the exception information:

  • Silence the exception by returning some True value.
  • Allow the exception to rise normally by returning any other False value. Returning nothing is the same as returning None, which is a False value; this allows the exception to propagate.

An exception might also be used to alter what the context manager does on exit. We might, for example, have to carry out special processing for certain types of OS errors that might arise.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset