🐍 Python for Everyone

← Back to all chapters

Chapter 12 of 27 Intermediate 45 min read

Exception Handling

Every program you've written so far assumes things go right — the user types a number when asked, the math works out, nothing unexpected happens. Real programs can't make that assumption. A user will type "twenty" instead of 20, a network request will fail, a file won't be where it's supposed to be. This chapter is about handling those moments on purpose, with try/except, instead of letting them crash your program.

How to read this chapter

Ask any user for their age and, sooner or later, someone will type "twenty" instead of 20. Without exception handling, that single bad keystroke crashes the entire program with a wall of red traceback text. With it, your program can notice the problem, say something helpful, and keep running — exactly the difference between software that feels broken and software that feels trustworthy.
Sub-topic 1 of 6

1. try/except basics

At a glance
  • An exception is an error that occurs while a program is running, and it normally stops the program immediately.
  • try/except lets a program attempt something risky and recover if it fails, instead of crashing.
  • Catching a specific exception type, like ValueError, is far better than guessing what might go wrong.
Why this matters: nothing you've written before this chapter has protected itself from bad input. int("twenty") simply crashes. This chapter is about no longer accepting that as the only option.

Converting text typed by a user into a number is one of the most common things a program does — and one of the easiest to get wrong, since a user can type absolutely anything:

crash_demo.py
age_text = "twenty"
age = int(age_text)
print("Age:", age)
actual output of crash_demo.py — the program stops here, nothing after this line runs
Traceback (most recent call last):
  File "crash_demo.py", line 2, in <module>
    age = int(age_text)
ValueError: invalid literal for int() with base 10: 'twenty'
What is... an exception? An exception is an error Python detects while a program is actually running (not before it starts, like a typo in your code). By default, an unhandled exception immediately stops the whole program and prints a traceback — the red error message showing exactly where things went wrong.

For a real program — a signup form, a checkout page, a game asking for a player's name — crashing on one bad keystroke is a terrible user experience. try/except wraps the risky line and gives Python somewhere to go instead of stopping outright:

try_except_basics.py
age_text = "twenty"

try:
    age = int(age_text)
    print("Age:", age)
except ValueError:
    print("That doesn't look like a valid number.")
actual output of try_except_basics.py — the program keeps running
That doesn't look like a valid number.
What is... try/except? try marks a block of code that might fail. If it fails with the exact exception type named in except, Python jumps straight into that except block instead of crashing. If nothing goes wrong, the except block is skipped entirely.

Naming ValueError specifically — instead of catching "anything" — matters. int("twenty") always raises a ValueError, so that's the one exception type this code needs to plan for; catching only what you expect keeps every other, genuinely unexpected bug visible instead of silently hidden.

try_try_except_basics.py
Click "Run Code" — try changing age_text to a real number like "20".
Go Deeper: only the exact line inside try that fails gets interrupted

If a try block has several lines, only the one that actually raises the exception gets cut short — everything before it in that block already ran and can't be undone. Any line after the failing one, still inside the same try block, is skipped, and Python jumps straight to except.

Quick recap
  • An unhandled exception crashes the program immediately and prints a traceback.
  • try marks risky code; a matching except catches the failure instead of crashing.
  • Name a specific exception type, like ValueError, rather than catching everything blindly.
Sub-topic 2 of 6

2. Multiple except blocks, else, and finally

At a glance
  • A single try can have multiple except blocks, each catching a different exception type.
  • else runs only if the try block succeeded with no exception at all.
  • finally always runs — whether the try succeeded, failed, or even re-raised an error.
Use this when: more than one thing could go wrong in the same block, and each failure deserves a different response — plus, separately, when some cleanup step must happen no matter what.

A single risky operation can fail in more than one way. Dividing two numbers can fail because of a zero, or because one value isn't a number at all — and each deserves its own message:

multiple_except.py
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Can't divide by zero.")
    except TypeError:
        print("Both values need to be numbers.")
    else:
        print("Result:", result)
    finally:
        print("Division attempt finished.")

safe_divide(10, 2)
print("---")
safe_divide(10, 0)
print("---")
safe_divide(10, "two")
actual output of multiple_except.py — trace of which block runs each time
Result: 5.0
Division attempt finished.
---
Can't divide by zero.
Division attempt finished.
---
Both values need to be numbers.
Division attempt finished.

Python checks except blocks top to bottom and stops at the first one that matches. Order matters here in exactly the way it doesn't for most Python code:

What is... else (in a try statement)? else runs only when the try block finished with no exception raised at all. It's a way to separate "code that might fail" (in try) from "code that should only run after success" (in else) — keeping the risky line by itself makes it obvious exactly what's being protected.
What is... finally? finally runs no matter what happened above it — success, a caught exception, or even an exception that wasn't caught at all. It's built for cleanup work that must always happen, like closing a connection or logging that an attempt was made.

Notice in the output above: "Division attempt finished." printed all three times, including the two failure cases. That's finally doing exactly what it promises — running unconditionally, every single time.

try_multiple_except.py
Click "Run Code" — try calling safe_divide(5, 0) instead.
Go Deeper: one except block, several exception types

except (ZeroDivisionError, TypeError): catches both exception types with a single block, using a tuple, when they should be handled identically. Use this instead of separate blocks only when the response really is the same for both — if the messages differ, separate except blocks (as above) stay clearer.

Quick recap
  • Multiple except blocks can catch different exception types from the same try.
  • else runs only when try succeeded with no exception.
  • finally always runs, regardless of what happened above it.
Sub-topic 3 of 6

3. Accessing the exception object

At a glance
  • except ValueError as e stores the actual exception object in e, not just its type.
  • str(e) gives the exception's human-readable message.
  • An exception carries real information about what specifically went wrong, not just that something did.
Use this when: the generic "something went wrong" message isn't enough, and the exact reason a failure happened is worth showing or logging.

Every exception Python raises carries a message describing exactly what went wrong — as e is how that message gets captured, instead of being thrown away:

exception_object.py
values = ["12", "seven", "45"]

for text in values:
    try:
        number = int(text)
        print("Parsed:", number)
    except ValueError as e:
        print("Skipping", repr(text), "—", str(e))
actual output of exception_object.py
Parsed: 12
Skipping 'seven' — invalid literal for int() with base 10: 'seven'
Parsed: 45
What is... except ... as e? as e gives a name to the actual exception object that was raised, so it can be used inside the except block — most commonly by converting it to text with str(e) to see its message. e is just a variable name; any name would work, but e is the near-universal convention.

Without as e, an except ValueError: block can only react to "a ValueError happened" — it has no way to say which value failed or why. str(e) turns the exception object into the same message Python's own traceback would have shown, but usable inside your own message instead of crashing the program.

try_exception_object.py
Click "Run Code" — try adding another bad value to the list.
Go Deeper: an exception object is more than just its message

e.args holds the exception's raw arguments as a tuple (usually just the message), and type(e).__name__ gives the exception's type as a string, like "ValueError" — useful when one except block needs to report exactly which type it caught. Everyday code almost always just needs str(e), but knowing the object holds more is worth remembering.

Quick recap
  • except ValueError as e captures the exception object itself, not just its type.
  • str(e) gives the exception's human-readable message.
  • An exception object carries real, usable information about the specific failure.
Sub-topic 4 of 6

4. Raising exceptions deliberately

At a glance
  • raise SomeError("message") triggers an exception on purpose, instead of waiting for Python to raise one by accident.
  • Raising with a clear, specific message tells whoever catches it exactly what went wrong.
  • A bare raise inside an except block re-raises the same exception, after doing something with it first (like logging).
Use this when: your own function detects a problem that Python itself wouldn't catch — an age that's negative, a name that's blank — and needs to signal it the same way built-in exceptions do.

Not every invalid input triggers a built-in exception on its own. int("-5") succeeds just fine — a negative age is a problem your own code has to notice and reject deliberately:

raise_basic.py
def set_age(age):
    if age < 0:
        raise ValueError("age cannot be negative")
    return age

print(set_age(25))
print(set_age(-5))
actual output of raise_basic.py — the second call crashes the program, on purpose
25
Traceback (most recent call last):
  File "raise_basic.py", line 7, in <module>
    print(set_age(-5))
  File "raise_basic.py", line 3, in set_age
    raise ValueError("age cannot be negative")
ValueError: age cannot be negative
What is... raise? raise triggers an exception manually, at the exact line you choose, instead of waiting for Python to hit an error on its own. raise ValueError("age cannot be negative") both picks the exception type and supplies its message.

A raised exception behaves exactly like one Python raises automatically — it can be caught with try/except just like int("twenty") failing was caught back in Sub-topic 1. raise is simply how your own code participates in that same system.

Sometimes a function wants to react to a failure — log it, clean something up — but still let the caller decide what happens next. A bare raise, with nothing after it, re-throws the exact same exception that was just caught:

reraise.py
def load_setting(value):
    try:
        return int(value)
    except ValueError:
        print("Logged: couldn't parse setting", repr(value))
        raise

try:
    load_setting("not-a-number")
except ValueError:
    print("Caller decided to fall back to a default of 0.")
actual output of reraise.py
Logged: couldn't parse setting 'not-a-number'
Caller decided to fall back to a default of 0.
What is... re-raising? Re-raising means catching an exception, doing something with it (like printing a log message), and then letting the same exception continue upward with a bare raise — instead of swallowing it silently or replacing it with a new one.
try_raise.py
Click "Run Code" — try changing -1 to a valid age like 30.
Go Deeper: raising a completely different exception type

except ValueError: raise TypeError("...") is legal — an except block can raise a different exception type entirely, not just re-raise the one it caught. This is less common than a bare raise, and worth using sparingly: it's only clearer when the new exception type genuinely means something different to whoever catches it further up.

Quick recap
  • raise SomeError("message") triggers an exception on purpose, with your own message.
  • A raised exception can be caught with try/except exactly like a built-in one.
  • A bare raise inside except re-raises the same exception after reacting to it.
Sub-topic 5 of 6

5. Custom exception classes

At a glance
  • A custom exception is a new exception type you define yourself, for a problem specific to your own program.
  • It's defined with class SomeError(Exception): pass — a narrow, specific use of class, just for exceptions.
  • Catching a custom exception type is far more precise than catching a generic Exception.
Note on scope: general class design is Chapter 14's topic. The only class-related syntax this chapter uses is class SomeError(Exception): pass — defining your own exception type, and nothing more.

ValueError is honest but vague — it doesn't say which business rule was broken. A banking app rejecting a withdrawal that exceeds the balance is a problem specific to that program, and deserves its own exception name:

custom_exception.py
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(f"Cannot withdraw ${amount} from a ${balance} balance")
    return balance - amount

try:
    new_balance = withdraw(100, 250)
except InsufficientFundsError as e:
    print("Withdrawal failed:", e)
else:
    print("New balance:", new_balance)
actual output of custom_exception.py
Withdrawal failed: Cannot withdraw $250 from a $100 balance
What is... a custom exception class? A custom exception is a new exception type, defined with class InsufficientFundsError(Exception): pass. The (Exception) part means it inherits everything a normal exception already does (a message, being catchable, etc.); pass means nothing extra needs to be added — the name itself is the whole point.

Once defined, InsufficientFundsError behaves exactly like any built-in exception — it can be raised, caught, and carries a message via str(e), all the same as ValueError throughout this chapter.

The real payoff shows up when catching. A generic except Exception: catches an InsufficientFundsError — but it would just as happily catch a typo-caused TypeError or any other unrelated bug hiding in the same block:

generic_vs_custom.py
class InsufficientFundsError(Exception):
    pass

def withdraw_generic(balance, amount):
    if amount > balance:
        raise Exception("not enough money")
    return balance - amount

def withdraw_custom(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("not enough money")
    return balance - amount

try:
    withdraw_generic(100, 250)
except Exception:
    print("Caught the generic Exception — but so would ANY other error in this block.")

try:
    withdraw_custom(100, 250)
except InsufficientFundsError:
    print("Caught specifically an InsufficientFundsError — nothing else could trigger this except block.")
actual output of generic_vs_custom.py
Caught the generic Exception — but so would ANY other error in this block.
Caught specifically an InsufficientFundsError — nothing else could trigger this except block.

That precision is the whole reason custom exceptions exist: except InsufficientFundsError: can only ever fire for that one specific business rule, so it can never accidentally swallow an unrelated bug the way a generic except Exception: might.

try_custom_exceptions.py
Click "Run Code" — try changing the numbers so the withdrawal succeeds instead.
Go Deeper: custom exceptions can form their own family

Multiple custom exceptions can share a common parent — for example, class BankingError(Exception): pass, then class InsufficientFundsError(BankingError): pass and class AccountFrozenError(BankingError): pass. A single except BankingError: then catches any error in that whole family at once, while each specific type can still be caught individually elsewhere. This pattern is common in larger real-world codebases; a single flat custom exception is plenty for everything in this chapter.

Quick recap
  • A custom exception is defined with class SomeError(Exception): pass.
  • It behaves exactly like a built-in exception once defined — raisable, catchable, carries a message.
  • Catching a custom exception type is precise; catching generic Exception risks swallowing unrelated bugs too.
Sub-topic 6 of 6

6. Real-world exception handling in production

At a glance
  • Robust input validation combines everything this chapter covered: try/except, raise, and a custom exception.
  • A bare except: is dangerous — it catches everything, including things you almost never want to catch.
  • A caught error should be logged or reported usefully, never silently thrown away.
Pattern to remember: catch specific exception types, report every failure somehow, and never let a bare except: hide a bug you didn't even know existed.

A signup form validating ages needs to reject both kinds of bad input this chapter has covered — text that isn't a number at all, and a number that's technically valid but unrealistic (like a negative age):

robust_validation.py
class InvalidAgeError(Exception):
    pass

def parse_age(text):
    try:
        age = int(text)
    except ValueError:
        raise InvalidAgeError(f"'{text}' is not a whole number") from None
    if age < 0 or age > 130:
        raise InvalidAgeError(f"{age} is not a realistic age")
    return age

def process_signup(raw_ages):
    accepted = []
    for text in raw_ages:
        try:
            accepted.append(parse_age(text))
        except InvalidAgeError as e:
            print("Rejected entry:", e)
        finally:
            print("Checked entry:", repr(text))
    return accepted

results = process_signup(["34", "-5", "sixteen", "29"])
print("Accepted ages:", results)
actual output of robust_validation.py
Checked entry: '34'
Rejected entry: -5 is not a realistic age
Checked entry: '-5'
Rejected entry: 'sixteen' is not a whole number
Checked entry: 'sixteen'
Checked entry: '29'
Accepted ages: [34, 29]

Every bad entry gets rejected with a specific, useful reason instead of crashing the whole signup batch — and finally guarantees every entry gets logged as "checked," whether it passed or not. This is the shape real validation code takes: one custom exception, raised from more than one place, always caught by name.

It's tempting to write except: with no exception type at all, meaning "catch literally anything." This is a trap:

bare_except_danger.py
def get_age(text):
    try:
        return int(text)
    except:
        print("Something went wrong.")
        return None

print(get_age("25"))
print(get_age("abc"))
actual output of bare_except_danger.py
25
Something went wrong.
None
What is... a bare except:? A bare except:, with no exception type named, catches every possible exception — not just the ones the code actually anticipated. That includes things almost no program should ever silently swallow, like KeyboardInterrupt (raised when a user presses Ctrl+C to stop the program) or a plain typo in your own code that raises NameError.

The fix is always the same: name the specific exception type (or types) actually expected, exactly like every example earlier in this chapter — never a bare except:.

The other half of production-quality error handling is what happens after catching — silently doing nothing is barely better than crashing, since the problem still went unnoticed:

try_bringing_together.py
Click "Run Code" — try adding your own entries to the list.
Go Deeper: except Exception vs. bare except

except Exception: (naming Exception specifically) is meaningfully safer than a bare except: — it still catches nearly every error worth catching, but leaves a handful of severe, low-level signals like KeyboardInterrupt and SystemExit alone, since those inherit from BaseException rather than Exception. It's still far less precise than naming the exact exception type expected, but if a truly broad catch is ever unavoidable, except Exception: is the safer of the two broad options.

Quick recap
  • Robust validation combines try/except, raise, and a custom exception into one clear pattern.
  • A bare except: catches everything, including bugs and a user's Ctrl+C — always name a specific exception type instead.
  • A caught exception should be reported (printed, logged) — never silently swallowed with no trace.
In the Real World

Points to Remember

← All Chapters Take the Quiz →