Skip to content

Multiple Exceptions & Built-ins

Catching Multiple Exceptions

You can define as many exception blocks as you want, if you want to execute a special block of code for a special kind of error.

try:
  print(x / y)
except NameError:
  print("Variable x or y is not defined")
except ZeroDivisionError:
  print("Cannot divide by zero")
except Exception as e:
  print(f"Something else went wrong: {e}")

Common Built-in Exceptions in Python

Exception Cause
IndexError When an index of a sequence is out of range.
KeyError When a key is not found in a dictionary.
TypeError When a function or operation is applied to an object of incorrect type.
ValueError When a function gets an argument of correct type but improper value.
ImportError When an imported module is not found.
FileNotFoundError When a file or directory is requested but doesn't exist.

Industry Context

Handling specific exceptions makes your code easier to debug and more robust for the end-user.