Python errors¶

Syntax error¶

When the interpreter encounters a syntax error, it stops and points into the code the exact place where the error occurred.

In [1]:
def some_function()
    msg = "hello, world!"
    print(msg)
  Cell In[1], line 1
    def some_function()
                       ^
SyntaxError: expected ':'

Traceback¶

When the interpreter encounters a runtime error, it stops and displays the list of functions calls which led to the error, where the error occurred and what type of error it was. This is called the "traceback".

In [2]:
def favorite_ice_cream():
    ice_creams = [ "chocolate", "vanilla", "strawberry" ]
    print(ice_creams[3])

favorite_ice_cream()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[2], line 5
      2     ice_creams = [ "chocolate", "vanilla", "strawberry" ]
      3     print(ice_creams[3])
----> 5 favorite_ice_cream()

Cell In[2], line 3, in favorite_ice_cream()
      1 def favorite_ice_cream():
      2     ice_creams = [ "chocolate", "vanilla", "strawberry" ]
----> 3     print(ice_creams[3])

IndexError: list index out of range

Common built-in errors¶

An error having to do with the "grammar" or syntax of the program is called a SyntaxError. If the issue has to do with how the code is indented, then it will be called an IndentationError.

A NameError will occur if you use a variable that has not been defined, either because you meant to use quotes around a string, you forgot to define the variable, or you just made a typo.

Containers like lists and strings will generate errors if you try to access items in them that do not exist. This type of error is called an IndexError.

Trying to read a file that does not exist will give you an FileNotFoundError. Trying to read a file that is open for writing, or writing to a file that is open for reading, will give you an IOError.

Catching errors¶

If you do not want your program to stop when it encounters a given error, you can enclose in a try block the set of code which may raise the error, and add an except block which is executed only in such a case. The program resumes after the except block.

In [3]:
n = float(input('numerator (0 to stop): '))
while n:
    d = float(input('denominator: '))
    try:
        res = n/d
    except ZeroDivisionError:
        print('(division by 0)')
        res = "NA"
    print('=>', res)
    n = float(input('numerator (0 to stop): '))
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[3], line 1
----> 1 n = float(input('numerator (0 to stop): '))
      2 while n:
      3     d = float(input('denominator: '))

File ~/.cache/pypoetry/virtualenvs/pyplot-doc-VOfsvtlq-py3.11/lib/python3.11/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

The keywords try and except are used in a way similar to if and else. If nothing goes wrong, Python executes the code in the try block and then skips over the except block entirely. If any exceptions are raised in the try block, Python immediately jumps to the start of the except block and executes the code inside it.

In fact, it is possible to have several except block, some blocks handling a specific exception and possibly one general purpose except block that will be executed if not others have been executed (similar to the elif - else logic). To be exhaustive, for some advanced use cases, there can be an optional else block that will be only executed if no exception is raised in the try-block and an optional finally block executed whether or not exception has occured.

In [4]:
n = float(input('numerator (0 to stop): '))
while n:
    try:
        d = float(input('denominator: '))
        res = n/d
    except ZeroDivisionError:
        print('(division by 0)')
        res = "NA"
    except Exception:
        print('(unrecognized exception)')
        res = "NA"
    else:
        print('(result OK)')
    finally:
        print('(end of try)')
    print('=>', res)
    n = float(input('numerator (0 to stop): '))
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[4], line 1
----> 1 n = float(input('numerator (0 to stop): '))
      2 while n:
      3     try:

File ~/.cache/pypoetry/virtualenvs/pyplot-doc-VOfsvtlq-py3.11/lib/python3.11/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Raising errors¶

You can also raise errors by yourself.

In [5]:
def choice():
    n = int(input('Choose a number from 0 to 9: '))
    if (n<0) or (n>9):
        raise ValueError
    return n

try:
    n = choice()
    print('Your choice is:', n)
except ValueError:
    print('Forbidden choice')
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[5], line 8
      5     return n
      7 try:
----> 8     n = choice()
      9     print('Your choice is:', n)
     10 except ValueError:

Cell In[5], line 2, in choice()
      1 def choice():
----> 2     n = int(input('Choose a number from 0 to 9: '))
      3     if (n<0) or (n>9):
      4         raise ValueError

File ~/.cache/pypoetry/virtualenvs/pyplot-doc-VOfsvtlq-py3.11/lib/python3.11/site-packages/ipykernel/kernelbase.py:1186, in Kernel.raw_input(self, prompt)
   1184 if not self._allow_stdin:
   1185     msg = "raw_input was called, but this frontend does not support input requests."
-> 1186     raise StdinNotImplementedError(msg)
   1187 return self._input_request(
   1188     str(prompt),
   1189     self._parent_ident["shell"],
   1190     self.get_parent("shell"),
   1191     password=False,
   1192 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

Python Built-in Exceptions¶

Here is the list of the exceptions that the Python interpreter may raise :

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Questions ?¶