CodeMIRAI
0 XP

Exceptions and try/except

2 min read 5 runnable examples Quiz included

When something goes wrong while a program runs, Python raises an exception. Unhandled, it stops the program with an error message. With try and except, you can catch it and decide what happens instead.

try and except

Python
text = input("Enter a number: ")
try:
    number = int(text)
    print("Double is", number * 2)
except ValueError:
    print(f"'{text}' isn't a whole number.")
print("The program carries on.")

Python runs the try block. If a ValueError happens inside it, Python jumps to the except block instead of crashing.

Catch specific exceptions

Name the exceptions you expect, and handle each one appropriately:

Python
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Can't divide by zero.")
    except TypeError:
        print("Both values must be numbers.")

print(safe_divide(10, 2))
safe_divide(10, 0)
safe_divide(10, "two")

Common built-in exceptions

ExceptionRaised when
ValueErrora value has the right type but a wrong value: int("abc")
TypeErroran operation gets the wrong type: "a" + 1
ZeroDivisionErrordividing by zero
KeyErrora dictionary key doesn't exist
IndexErrora list index is out of range
FileNotFoundErroropening a file that isn't there
NameErrorusing a name that doesn't exist

Getting the error message

as gives you the exception object, whose message you can print or log:

Python
prices = {"tea": 20}
try:
    print(prices["coffee"])
except KeyError as error:
    print("Missing key:", error)

else and finally

  • else runs only if no exception happened.
  • finally runs always, whether there was an error or not. It's the place for clean-up.
try:did it raise an error?yesnoexcept: handle itelse: it workedfinally: always
except runs only after an error and else only without one; finally runs either way, which makes it the place to clean up.
Python
def parse_age(text):
    try:
        age = int(text)
    except ValueError:
        print(f"  {text!r}: not a number")
    else:
        print(f"  {text!r}: age {age}")
    finally:
        print("  (checked)")

parse_age("42")
parse_age("forty")

Keep asking until the input is valid

Python
while True:
    try:
        n = int(input("Positive number: "))
        if n <= 0:
            print("It must be positive.")
            continue
        break
    except ValueError:
        print("That's not a number.")
print("You chose", n)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.