
上QQ阅读APP看书,第一时间看更新
Handling exceptions
Exceptions that arise in a 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 returningNone
, which is aFalse
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 do special processing for certain types of OS errors that might arise.