Error and Exception Handling · 4 / 20 Theory

Exception types and how to read an error

Each Python error is of a different type, and telling them apart lets you react differently to each one.

The most common exceptions

ExceptionWhen it happensExample
ValueErrorThe type is right but the value is not validint("abc")
TypeErrorOperation with an unsuitable type"a" + 1
ZeroDivisionErrorDivision by zero5 / 0
IndexErrorPosition that does not exist in a list or string[1, 2][5]
KeyErrorKey that does not exist in a dictionary{"a": 1}["b"]
NameErrorUndefined variableprint(x)
FileNotFoundErrorThe file does not existopen("no.txt")
AttributeErrorThe object does not have that attribute or method"hello".push()

Catching different errors differently

You can put several except; Python uses the first one that matches:

try:
    text = input()
    divisor = int(input())
    print(int(text) / divisor)
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Cannot divide by zero")

It is the scheme of Handling multiple exceptions.

Catching several types with the same message

try:
    value = items[int(input())]
except (ValueError, IndexError):
    print("Invalid input")

Saving the exception with as

as gives a name to the exception object, which contains the error message:

try:
    int("abc")
except ValueError as error:
    print(error)           # invalid literal for int() with base 10: 'abc'
    print(type(error))     # <class 'ValueError'>

The exception hierarchy

Exceptions form a family: some inherit from others. For example, ZeroDivisionError is an ArithmeticError, and all of them inherit from Exception:

print(issubclass(ZeroDivisionError, ArithmeticError))   # True
print(issubclass(ValueError, Exception))             # True

Catching an exception also catches its children. That is why the order matters: the most specific except must go before the general one. If you put except Exception first, the others are never reached.

try:
    10 / 0
except ZeroDivisionError:
    print("division by zero")   # this one is used
except Exception:
    print("other error")

How to read a traceback

If an exception is not caught, Python prints a traceback: the path the program followed up to the error. It is read from bottom to top; the last line is the most important:

Traceback (most recent call last):
  File "program.py", line 6, in <module>
    result = calculate(10, 0)
  File "program.py", line 2, in calculate
    return a / b
ZeroDivisionError: division by zero
  • Last line: the error type (ZeroDivisionError) and its message.
  • Line before: where exactly it happened (line 2, inside calculate).
  • The ones above: who called whom until getting there.

Practice with Safe integer and Safe index.