Python: Exceptions

Exception is a standard way of propagating errors.

Exceptions:

  • Has hierarchy
  • Can be chained (__cause__, __context__)

Best practice:

  1. DON’T catch an exception if it cannot be handled at that specific location.
  2. DO make except clause as narrow as reasonable.
  3. 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 in var.
  • An exception was raised: 3 args of __exit__(type, value, traceback) are populated.

contextlib module has useful functions:

  • closing
  • suppress
  • redirect_(stdout|stderr)
  • ExitStack
  • nullcontext

Leave a comment