10. Exceptions

10.1 Overview

  • When there’s an error in a Python code, the output includes a Traceback. This often helps you identify and trace the error.

  • To catch an error, use try blocks.

try:
    x = int('foo')
except ValueError:
    print('I caught a ValueError')
else:
    print('good job!') # only executed if there is no error
  • ValueError is just one type of error.

  • Other errors include ZeroDivisionError

  • If error type is not known, simply use except: without specifying the type of error.

  • Python has a rich and complete system for handling exceptions.

10.2 Reporting

  • Think of exceptions as a way to describe runtime errors.

  • Generate an exception using raise:

# initialize parameters
if numargs < 1:
    raise TypeError(f'expected at least 1 argument, got {numargs}')
  • Such exceptions can also be caught in a try block.