Exceptions

Syntax errors, built-in and user-defined exceptions; raising and catching them.

Computer Science/Informatics Practices5 questions

The essentials

Errors in a Python program are of two broad kinds. Syntax errors (parsing errors) break the rules of the language, such as a missing colon or bracket; Python reports them before running the program. Exceptions are errors that occur during execution even when the syntax is correct, such as dividing by zero. When an exception occurs and is not handled, the program stops and Python shows a traceback.

Key points

  • ZeroDivisionError: division or modulo by zero, as in 10/0.
  • ValueError: right type but unsuitable value, as in int('abc').
  • TypeError: an operation applied to the wrong type, as in '5' + 5.
  • NameError: a variable or name that has not been defined is used.
  • IndexError: a sequence index is out of range, as in [1, 2, 3][5].
  • KeyError: a dictionary key is not found.
  • IndentationError: wrong indentation (a kind of syntax error).
  • FileNotFoundError / IOError: a file cannot be opened, for example opening a missing file in read mode.
  • EOFError: input or loading reaches end of file with no data.
  • ImportError: a module cannot be imported.
  • raise statement: throws an exception deliberately: raise ValueError("Negative marks").
  • assert statement: assert condition, message raises AssertionError if the condition is False.
  • User-defined exceptions: a programmer can create a new exception class derived from Exception, such as class LowBalanceError(Exception): pass, and then raise it.

Exam tips

  • Match the code to the error name; examiners often pick TypeError versus ValueError.
  • Remember that an exception object carries a message, which can be printed in the handler.

Common mistakes

  • Calling a missing colon an exception. It is a syntax error, found before execution.
  • Thinking raise can only be used with built-in exceptions.

Practice questions

Practice this topic