Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Python Exception Handling
Python Beginner FREE

Exception Handling

Lesson 1 of 14 Beginner Interactive

try/except catches errors gracefully. else runs on success; finally always runs.

Raising Exceptions

raise ValueError("msg")

Custom Exceptions

Inherit from Exception to create custom error types.

Syntax

PYTHON
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except (ValueError, TypeError) as e:
    print(f"Error: {e}")
else:
    print(f"Result: {result}")
finally:
    print("Cleanup")
Python Exception Handling
PYTHON
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError:
        return "Invalid types"
    else:
        return f"Result: {result}"
    finally:
        print("Cleanup done")

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

# Custom exception
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough funds")
    return balance - amount

try:
    withdraw(100, 200)
except InsufficientFundsError as e:
    print("Error:", e)

Practice

1
Exercise

Create custom InvalidEmailError.

Answer
class InvalidEmailError(Exception): pass
def validate(email):
    if "@" not in email: raise InvalidEmailError(email)

Quick Quiz

1

When does finally execute?

Finally always runs.

Interview Questions

EAFP (try/except) is Pythonic for exceptional cases. LBYL (if check) for expected conditions.