Module 2 of 5 · Python Fundamentals Part 2 · Beginner

Exception Handling

Duration: 5 min

What are Exceptions?

An exception is an error that occurs during program execution. Python provides a way to handle these exceptions gracefully using try-except blocks. This prevents your program from crashing when an error occurs.

try-except Blocks

# Basic try-except
try:
    number = int("abc")  # This will raise an error
except ValueError:
    print("Error: Invalid number")

# Catching multiple exceptions
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero")
except ValueError:
    print("Error: Invalid value")

# Generic exception
try:
    x = [1, 2, 3]
    print(x[10])
except Exception as e:
    print(f"An error occurred: {e}")

Try it in Google Colab: Open in Colab

Error: Invalid number
Error: Cannot divide by zero
An error occurred: list index out of range

try-except-finally

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Error: File not found")
finally:
    print("Cleanup code runs regardless")
    # file.close() would go here
Error: File not found
Cleanup code runs regardless

Raising Exceptions

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Age is unrealistic")
    return f"Valid age: {age}"

try:
    print(validate_age(25))
    print(validate_age(-5))
except ValueError as e:
    print(f"Error: {e}")
Valid age: 25
Error: Age cannot be negative

💡 Tip: Always catch specific exceptions rather than using a bare except clause. This helps you understand what went wrong.

Learn more: https://docs.python.org/3/tutorial/errors.html

❓ What does the finally block do?

← Previous Continue interactively → Next →

Related Courses