Lesson 1 of 5 · Errors and Files · 3 min read · Updated

Handling errors with try and except

Catching an error so the program can recover instead of crashing.

When something goes wrong at run time, Python raises an exception. Unhandled, it stops the program with a traceback. Wrapped in try, you decide what happens instead.

python
values = ["42", "abc", "7"]
for text in values:
    try:
        number = int(text)
        print(number * 2)
    except ValueError:
        print(f"'{text}' is not a number")
Output
84
'abc' is not a number
14

The bad value was handled and the loop carried on to the next one. Name the exception you expect — here ValueError, which is what int() raises for text that is not a number.

else, finally and several excepts

python
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError as e:
        return f"Bad input: {e}"
    else:
        return result
    finally:
        print("checked", a, b)

print(safe_divide(10, 2))
print(safe_divide(1, 0))
print(safe_divide("1", 2))
Output
checked 10 2
5.0
checked 1 0
Cannot divide by zero
checked 1 2
Bad input: unsupported operand type(s) for /: 'str' and 'int'
  • Each except handles one kind of error; the first that matches runs.
  • as e keeps the exception, so you can show its message.
  • else runs only if nothing went wrong.
  • finally runs no matter what — even after a return. Use it for clean-up.

Asking until the answer is valid

python
while True:
    try:
        age = int(input("Age: "))
        break
    except ValueError:
        print("Please type a whole number.")

print("Thanks, you are", age)
Output
Age: twenty
Please type a whole number.
Age: 20
Thanks, you are 20

Warning

Never write a bare except: with no exception name. It also catches your own typos, such as a misspelt variable, and silently hides them. Catch the specific exception you expect.

Exceptions you will meet often

  • ValueError — right type, wrong value, such as int("abc").
  • TypeError — wrong type, such as "a" + 1.
  • KeyError / IndexError — a missing dictionary key or list position.
  • ZeroDivisionError, FileNotFoundError, NameError.

When does the finally block run?

Try this now

  1. Ask for two numbers and divide them, handling both a non-number and division by zero with clear messages.
  2. Look up a name in a dictionary with square brackets, catching KeyError to print "Not found".

Create a free account to save your progress, or sign in.