Tutorials / Python Basics / Lesson 14

Handling Errors

What You Will Learn

Errors happen — files do not exist, users type the wrong thing, network requests fail. In this lesson, you will learn how to handle errors gracefully instead of letting your program crash.


What Happens Without Error Handling

age = int(input("Enter your age: "))
print(f"You are {age} years old.")

If the user types “hello” instead of a number:

Enter your age: hello
ValueError: invalid literal for int() with base 10: 'hello'

The program crashes. Not great.


try / except

Wrap the risky code in a try block, and handle the error in except:

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("Please enter a valid number.")

Example interaction (bad input):

Enter your age: hello
Please enter a valid number.

The program continues instead of crashing.


Catching Specific Errors

Always catch the specific error type you expect:

# File might not exist
try:
    with open("data.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found. Starting fresh.")
    content = ""

# Division by zero
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

The else Clause

else runs only if no error occurred:

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("That was not a number.")
else:
    print(f"Your number doubled: {number * 2}")

The finally Clause

finally always runs, whether or not an error occurred. Use it for cleanup:

try:
    f = open("data.txt", "r")
    content = f.read()
except FileNotFoundError:
    print("File not found.")
finally:
    print("Done attempting to read file.")

Asking Again Until Valid Input

Combine while True with try/except to keep asking until the user gives valid input:

while True:
    try:
        age = int(input("Enter your age: "))
        if age < 0 or age > 150:
            print("Age must be between 0 and 150.")
            continue
        break
    except ValueError:
        print("Please enter a whole number.")

print(f"Your age is {age}.")

Example interaction:

Enter your age: hello
Please enter a whole number.
Enter your age: -5
Age must be between 0 and 150.
Enter your age: 25
Your age is 25.

Common Exception Types

ExceptionWhen it occurs
ValueErrorWrong type of value (e.g. int("hello"))
TypeErrorWrong type for an operation
FileNotFoundErrorFile does not exist
ZeroDivisionErrorDividing by zero
IndexErrorList index out of range
KeyErrorDictionary key does not exist

What You Learned

  • try/except catches errors and prevents crashes
  • Always catch the specific exception type
  • else runs when no error occurred
  • finally always runs — useful for cleanup
  • Combine with while True to retry on bad input

In the final lesson, you will put everything together and build a complete command-line application.