Skip to content
AgileLogics
4 min read

Basic Error Handling

Prerequisites: Functions

An error that happens while a program is running is called an exception. try/except lets you catch one and respond instead of letting the whole program crash.

try:
    number = int(input("Enter a number: "))
    print(100 / number)
except ValueError:
    print("That wasn't a valid number.")
except ZeroDivisionError:
    print("Can't divide by zero.")

Python tries the try block first; if a matching exception is raised, it jumps straight to the matching except block instead of crashing.

Common mistakes

  • Writing a bare except: that catches everything, silently hiding bugs you'd want to know about. Catch the specific exception you expect.