Exceptions

Published

2023-08-01

Exceptions

Exceptions are errors that occur at run time, that is, when you run your code. When such an error occurs Python raises an exception, prints a message with information about the exception, and then halts execution. Exceptions have different types, and this tells us about the kind of error that’s occurred.

If there is a syntax error, an exception of type SyntaxError is raised. If there is an indentation error (a more specific kind of syntax error), an IndentationError is raised. These errors occur before your code is ever run—they are discovered as Python is first reading your file.

Most other exceptions occur as your program is run. In these cases, the message will include what’s called a traceback, which provides a little information about where in your code the error occurred. The last line in an exception message reports the type of exception that has occurred. It’s often helpful to read such messages from the bottom up.

What follows are brief summaries of the first types of exceptions you’re likely to encounter, and in each new chapter, we’ll introduce new exception types as appropriate.

SyntaxError

If you write code which does not follow the rules of Python syntax, Python will raise an exception of type SyntaxError. Example:

>>> 1 + / 1
  File "<stdin>", line 1
    1 + / 1
        ^
SyntaxError: invalid syntax

Notice that the ^ character is used to indicate the point at which the error occurred.

Here’s another:

>>> True False
  File "<stdin>", line 1
    True False
         ^
SyntaxError: invalid syntax

When you encounter a syntax error, it means that some portion of your code does not follow the rules of syntax. Code which includes a syntax error cannot be executed by the Python interpreter, and syntax errors must be corrected before your code will run.

NameError

A NameError occurs when we try to use a name which is undefined. There must be a value assigned to a name before we can use the name.

Here’s an example of a NameError:

>>> print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Notice that Python reports the NameError and informs you of the name you tried to use but which is undefined (in this case x).

These kinds of errors most often occur when we’ve made a typo in a name.

Depending on the root cause of the error, there are two ways to correct these errors.

  • If the cause is a typo, just correct your typo.
  • If it’s not just a typo, then you must define the name by making an assignment with the appropriate name.
>>> pet = 'rabbit'
>>> print(pot)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pot' is not defined
>>> print(pet)
rabbit
>>> age = age + 1  # Happy birthday!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'age' is not defined
>>> age = 100
>>> age = age + 1  # Happy birthday!
>>> print(age)
101

TypeError

A TypeError occurs when we try to perform an operation on an object which does not support that operation.

The Python documentation states: “[TypeError is] raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.”1

For example, we can perform addition with operands of type int using the + operator, and we can concatenate strings using the same operator, but we cannot add an int to a str.

>>> 2 + 2
4
>>> 'fast' + 'fast' + 'fast'
'fastfastfast'
>>> 2 + 'armadillo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

When you encounter a TypeError, you must examine the operator and operands and determine the best fix. This will vary on a case-by-case basis.

Here are some other examples of TypeError:

>>> 'hopscotch' / 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>> 'barbequeue' + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

ZeroDivisionError

Just as we cannot divide by zero in mathematics, we cannot divide by zero in Python either. Since the remainder operation (%) and integer (a.k.a. floor) division (//) depend on division, the same restriction applies to these as well.

>>> 1000 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).