New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Python› Error Handling with Exceptions

Error Handling with Exceptions

💻 Python

Catch errors, raise your own and keep programs running when something goes wrong.

Lesson 8 of 9 Tutorial
0 of 9 completed

Errors are normal. A missing file, bad input or network failure should produce a clear message, not a crash.

By the end of this lesson you can:
  • Use try, except, else and finally.
  • Catch specific exceptions.
  • Raise exceptions for invalid input.

try and except

Put risky code inside try. If it raises an exception, the matching except block runs and the program continues.

try:
    age = int(input("Your age: "))
    print(f"You will be {age + 1} next year.")
except ValueError:
    print("Please enter a number.")

Specific Exceptions

Catch the exception you expect. A bare except: hides bugs, including spelling mistakes in your own code.

try:
    with open("scores.txt") as file:
        scores = [int(line) for line in file]
except FileNotFoundError:
    scores = []
    print("No scores file yet. Starting empty.")
except ValueError:
    print("The file contains something that is not a number.")

Raising Errors

Use raise when a caller passes something invalid. The message should tell the caller what to fix.

def set_score(score):
    if not 0 <= score <= 100:
        raise ValueError("Score must be between 0 and 100")
    return score

try:
    set_score(140)
except ValueError as error:
    print("Rejected:", error)

finally

finally always runs, whether or not an error occurred. Use it to close files or release resources.

Tip Read the last line of a Python traceback first. It names the exception type and the actual problem.

Practice

  1. Ask for a number and handle invalid input.
  2. Open a file that may not exist and provide a fallback.
  3. Raise a ValueError for an empty name.

Hands-on exercise

Write a function safe_divide(a, b).
1. Return a / b.
2. If b is zero, return None and print a clear message.
3. Test it with 10 / 2 and 10 / 0.

Recap

Catch only what you expect, give useful messages and raise errors early when input is invalid.

Example

try:
    age = int(input("Your age: "))
    print(f"You will be {age + 1} next year.")
except ValueError:
    print("Please enter a number.")

Exercises

Exercise 1. Safe divide Easy
Write a function safe_divide(a, b).
1. Return a / b.
2. If b is zero, return None and print a clear message.
3. Test it with 10 / 2 and 10 / 0.
Python exercise-1.py
Expected Output
5.0
Cannot divide by zero.
None

Lesson Nav

Lesson sections