try and except

Catching errors

Normally an error stops your program. With try and except you can catch the error and decide what to do instead.

try:
    number = int("hello")
    print("You typed", number)
except ValueError:
    print("That's not a number!")
print("The program keeps going.")

Output

That's not a number!
The program keeps going.
  • Python tries to run the code in the try block.
  • If a ValueError happens, it jumps straight to the except block.
  • If nothing goes wrong, the except block is skipped.

Think of it like this: A safety net under a tightrope walker. If they fall, the net catches them and the show goes on.

A friendly calculator

try:
    a = int(input("First number: "))
    b = int(input("Second number: "))
    print("Answer:", a / b)
except ValueError:
    print("Please type whole numbers only.")
except ZeroDivisionError:
    print("You can't divide by zero.")

Output (when you type 10 and 0)

First number: 10
Second number: 0
You can't divide by zero.

You can have several except blocks, one for each kind of error.

Asking again until it works

while True:
    try:
        age = int(input("Your age: "))
        break
    except ValueError:
        print("Numbers only, please.")
print("Thanks! You are", age)

Output (when you type twenty, then 20)

Your age: twenty
Numbers only, please.
Your age: 20
Thanks! You are 20

Seeing the error message

try:
    print(10 / 0)
except ZeroDivisionError as error:
    print("Something went wrong:", error)

Output

Something went wrong: division by zero

Common mistake: A bare except: with no error type catches everything, including mistakes in your own code, which hides bugs. Always name the error you expect.

HOME LEARN COMMUNITY DASHBOARD