Exceptions

Published

2023-07-31

Exceptions

IndentationError

In Python, unlike many other languages, indentation is syntactically significant. We’ve seen when defining a function that the body of the function must be indented (we’ll see other uses of indentation soon).

An exception of type IndentationError is raised if Python disagrees with your use of indentation—typically if indentation is expected and your code isn’t, or if a portion of your code is over-indented. IndentationError is a more specific type of SyntaxError.

When you encounter an indentation error, you should inspect your code and correct the indentation.

Here’s an example:

>>> def square(n):
... return n * n
  File "<stdin>", line 2
    return n * n
    ^
IndentationError: expected an indented block after function 
                      definition on line 1
>>> def square(n):
...     return n * n  # now it's correctly indented!
... 
>>> square(4)
16

ValueError

A ValueError is raised when the type of an argument or operand is valid, but the value is somehow unsuitable. We’ve seen how to import the math module and how to use math.sqrt() to calculate the square root of some number. However, math.sqrt() does not accept negative operands (it doesn’t know about complex numbers), and so, if you supply a negative operand to math.sqrt() a ValueError is raised.

Example:

>>> import math
>>> math.sqrt(4)  # this is A-OK
2.0
>>> math.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

In a case like this, you need to ensure that the argument or operand which is causing the problem has a suitable value.

ModuleNotFoundError

We encounter ModuleNotFoundError if we try to import a module that doesn’t exist, that Python can’t find, or if we misspell the name of a module.

Example:

>>> import maath
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maath'

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).