Exception is a standard way of propagating errors.
Exceptions:
- Has hierarchy
- Can be chained (
__cause__,__context__)
Best practice:
- DON’T catch an exception if it cannot be handled at that specific location.
- DO make
exceptclause as narrow as reasonable. - DO make your own exception if you are explicitly raising.
class MyException(Exception):
def __init__(self, errno, msg):
# self.args is used when printing traceback
self.args = (errno, msg)
self.errono = errno
self.msg = msg
Context Manager helps with resources that need closing even on exceptions.
__exit__returns True: Exception has been handled and should no longer propagate.as var: Value returned by__enter__is placed invar.- An exception was raised: 3 args of
__exit__(type, value, traceback)are populated.
contextlib module has useful functions:
closingsuppressredirect_(stdout|stderr)ExitStacknullcontext
Leave a comment