Python - Exceptions
Last Updated: 2254Z 13AUG20 (Created: 1825Z 23SEP19)

Exceptions are part of the standard flow control strategy of Python; ex iterators raise StopIteration when exhausted.

Use try/except to catch expected exceptions and do something smart with them; Unexpected exceptions are bug reports.

Signatures:

None
import logging

# standard search for item in items
try:
    something()

except <Expected Exception>:
    logging.<level>("something")    # see [8] for standard levels

except (<Expected Exception 1>, <Expected Exception 2>, <Expected Exception n>):
    pass

except <Expected Exception> as err:
    print("OS error: {0}".format(err))
    logging.exception(err)      # notes

except:
    # DO NOT DO THIS, EVER! [3]
    pass

finally:
    # Always executes [2]
    cleanup()

Examples:

# Simple
config_dict = {}

try:
    print(config_dict['DEFAULT_LOG_LEVEL'])

except KeyError:
    print('Key Error')

# output: 'Key Error'

# Full
try:
    1/0

except ZeroDivisionError as err:
    print('Handling run-time error:', err)  # output: Handling run-time error: division by zero

except Exception as err:
    print(type(err))                        # the exception instance
    print(err.args)                         # arguments stored in .args
    print(err)                              # __str__ allows args to be printed directly
    x, y = err.args                         # unpack args

finally:
    # always executed as last task before try statement completes. eg use for cleanup
    print('Goodbye, world!')

References:

  1. https://docs.python.org/3/tutorial/errors.html#handling-exceptions
  2. https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions
  3. https://realpython.com/the-most-diabolical-python-antipattern/
  4. https://docs.python.org/3/library/exceptions.html#bltin-exceptions
  5. https://docs.python.org/3/library/logging.html#logger-objects
  6. https://www.loggly.com/blog/exceptional-logging-of-exceptions-in-python/
  7. https://realpython.com/python-logging/
  8. https://docs.python.org/3.8/howto/logging.html