← Back to Python Course | Chapter 10: Exception Handling | Lesson 1 of 5

Python Exception Handling

What is an Exception?

An exception is an error Python detects while your program is running (as opposed to a syntax error caught before it even starts) -- if nothing handles it, the exception propagates up and crashes the program with a traceback, which is why handling matters for code that shouldn't just stop unexpectedly.

Example: What is an Exception?

python
try:
    print(1 / 0)
except ZeroDivisionError:
    print("Caught an exception instead of crashing")

Built-in Exceptions

Python ships with many specific built-in exception types -- ZeroDivisionError, TypeError, ValueError, and more -- and catching the specific type you expect (rather than a bare except) makes your error handling precise instead of accidentally swallowing unrelated bugs.

Example: Built-in Exceptions

python
try:
    int("abc")
except ValueError:
    print("Caught a specific ValueError")

Raising Exceptions

The raise keyword lets your own code deliberately trigger an exception, which is how you signal 'this input is invalid' from deep inside a function -- raise ValueError('age must be positive') stops execution there and lets a caller's except block decide how to respond.

Example: Raising Exceptions

python
def set_age(age):
    if age < 0:
        raise ValueError("age must be positive")
    return age

try:
    set_age(-5)
except ValueError as e:
    print(e)

Creating Custom Exceptions

Subclassing the built-in Exception class lets you create your own exception types specific to your application's domain (like InsufficientFundsError), which makes error handling code more readable than checking for generic exceptions and guessing what actually went wrong.

Example: Creating Custom Exceptions

python
class InsufficientFundsError(Exception):
    pass

try:
    raise InsufficientFundsError("Not enough balance")
except InsufficientFundsError as e:
    print(e)

Exception Hierarchy

Every built-in exception ultimately inherits from the base Exception class, so an except Exception: block will catch essentially any error your code raises -- but catching that broadly is usually too blunt for production code, since it also hides bugs you'd want to know about.

Example: Exception Hierarchy

python
try:
    int("abc")
except Exception as e:
    print("Caught by the base Exception class:", type(e).__name__)
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.