🛡️

How to Handle Exceptions in Python

PythonIntermediate

Catch and handle errors gracefully with try/except.

Code Example

Python
# Basic try/except
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Cannot divide by zero")

# Multiple exceptions
try:
    number = int("abc")
except ValueError:
    print("Error: Invalid number format")
except TypeError:
    print("Error: Wrong type")

# Catch all exceptions
try:
    risky_operation = 1 / 0
except Exception as e:
    print(f"Error occurred: {e}")

# Try/except/else/finally
try:
    result = 10 / 2
except ZeroDivisionError:
    print("Division by zero")
else:
    print(f"Success! Result: {result}")
finally:
    print("This always executes")

# Raise exceptions
def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

try:
    validate_age(-5)
except ValueError as e:
    print(f"\nValidation error: {e}")

Explanation

Use try/except to catch errors. Multiple except blocks handle different error types. Else runs if no exception, finally always runs.

Related Tutorials