Velamuvi AIAcademy

Lesson 26 of 30 · Files, Errors and Modules

Handling Errors

Stop your Python programs from crashing. Learn try, except, else and finally, how to catch specific errors and how to raise your own.

  • 8 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • What an exception is
  • How to catch errors with try and except
  • How to handle different errors in different ways
  • How to raise an error yourself

Errors that happen while the program runs

Some errors cannot be prevented by writing careful code. A user types letters where a number was expected. A file is missing. The internet connection drops. These problems appear while the program is running, and Python reports them as exceptions.

By default, an exception stops the program immediately.

Try it yourselfPython
age = int(input("How old are you? "))
print("Next year you will be", age + 1)

The user typed twenty, int() could not convert it, and the program stopped with a ValueError. The second line never ran. A real application cannot behave like this.

try and except

Put the risky code in a try block. If an exception happens there, Python jumps to the except block instead of stopping.

Try it yourselfPython
try:
    age = int(input("How old are you? "))
    print("Next year you will be", age + 1)
except ValueError:
    print("Please type your age as a number, for example 20.")

print("The program is still running.")

Change the input to 20 and run it again. When nothing goes wrong, the except block is skipped.

Catch the specific error

Always name the error you expect. Different problems deserve different responses, and you can add several except blocks.

Try it yourselfPython
def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError:
        return "Both values must be numbers"

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

These are the exceptions you have met in this course.

ExceptionCauseExample
ValueErrorRight type, wrong valueint("hello")
TypeErrorWrong type"age" + 5
NameErrorUnknown variable nameprint(totl)
IndexErrorList position does not existitems[99]
KeyErrorDictionary key does not existperson["email"]
ZeroDivisionErrorDividing by zero10 / 0
FileNotFoundErrorFile does not existopen("missing.txt")

Reading the error message

Add as error to get the exception's own message, which is useful to show or record.

Try it yourselfPython
try:
    with open("missing.txt") as file:
        print(file.read())
except FileNotFoundError as error:
    print("Could not open the file.")
    print("Details:", error)

else and finally

Two optional blocks complete the picture.

  • else runs only if the try block had no error.
  • finally runs always, error or not. It is used for tidying up.
Try it yourselfPython
def read_number(text):
    try:
        number = int(text)
    except ValueError:
        print(f"'{text}' is not a number.")
    else:
        print(f"Got the number {number}.")
    finally:
        print("Finished checking.")

read_number("42")
read_number("abc")

Asking again until the input is valid

Combine try with a while True loop to keep asking until the user gets it right.

Try it yourselfPython
while True:
    try:
        age = int(input("Your age: "))
    except ValueError:
        print("That is not a number. Try again.")
        continue
    if age < 0:
        print("Age cannot be negative. Try again.")
        continue
    break

print("Thank you. Age recorded:", age)

Raising your own errors

Use raise to signal that something is wrong in your own code. This stops a bad value from travelling further into the program.

Try it yourselfPython
def set_price(price):
    if price < 0:
        raise ValueError("Price cannot be negative")
    return price

try:
    set_price(-5)
except ValueError as error:
    print("Error:", error)

Common mistakes

Practice exercise

Make safe_divide return a friendly message instead of crashing when the second number is zero.

Your solutionPython
def safe_divide(a, b):
    # Return a / b.
    # If b is zero, return the text: Cannot divide by zero
    return a / b

# Do not change these two lines. Output must be exactly:
# 5.0
# Cannot divide by zero
print(safe_divide(10, 2))
print(safe_divide(10, 0))
Knowledge check

When does the code in an except block run?

Summary

  • An exception is an error that happens while a program runs.
  • try holds the risky code, and except says what to do if it fails.
  • Name the specific exception: except ValueError:.
  • else runs when there was no error, and finally always runs.
  • raise creates an exception of your own.

Next: using code that other people have already written.

Finished reading? Tick it off to track your progress.