Python | Exceptions

Exceptions occur when something goes wrong (incorrect code or input) and they cause the program to stop.

Example:

>>> num1 = 5
>>> num2 = 0
>>> print(num1/num2)
Traceback (most recent call last):
  File "", line 1, in 
ZeroDivisionError: integer division or modulo by zero
>>> 

The code causes a ZeroDivisionError since division by zero is not possible.

List of common exceptions in Python:

  • ImportError – an import fails
  • IndexError – a list is indexed with an out-of-range number
  • NameError – an unknown variable is used
  • SyntaxError – the code can’t be parsed properly
  • TypeError – a function is called on a value of an inappropriate type
  • ValueError – a function is called on a value of the correct type, but with an inappropriate value

Note:
Third-party libraries also often define their own exceptions.

Leave a Reply