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
- An exception is Python's way of saying "something went wrong here."
try/exceptlets your program notice that and respond, instead of stopping dead. - Sub-topics build on each other — basics first, then the full
else/finallypicture, then raising your own exceptions, then defining your own exception types. - This is where "robust" code starts to mean something concrete — handling bad input gracefully is one of the clearest lines between a beginner script and production-ready code.
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.
1. try/except basics
- An exception is an error that occurs while a program is running, and it normally stops the program immediately.
try/exceptlets 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.
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:
age_text = "twenty"
age = int(age_text)
print("Age:", age)
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'
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:
age_text = "twenty"
try:
age = int(age_text)
print("Age:", age)
except ValueError:
print("That doesn't look like a valid number.")
That doesn't look like a valid number.
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.
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.
- An unhandled exception crashes the program immediately and prints a traceback.
trymarks risky code; a matchingexceptcatches the failure instead of crashing.- Name a specific exception type, like
ValueError, rather than catching everything blindly.
2. Multiple except blocks, else, and finally
- A single
trycan have multipleexceptblocks, each catching a different exception type. elseruns only if thetryblock succeeded with no exception at all.finallyalways runs — whether thetrysucceeded, failed, or even re-raised an error.
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:
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")
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:
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.
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.
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.
- Multiple
exceptblocks can catch different exception types from the sametry. elseruns only whentrysucceeded with no exception.finallyalways runs, regardless of what happened above it.
3. Accessing the exception object
except ValueError as estores the actual exception object ine, 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.
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:
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))
Parsed: 12
Skipping 'seven' — invalid literal for int() with base 10: 'seven'
Parsed: 45
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.
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.
except ValueError as ecaptures 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.
4. Raising exceptions deliberately
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
raiseinside anexceptblock re-raises the same exception, after doing something with it first (like logging).
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:
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
print(set_age(25))
print(set_age(-5))
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
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:
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.")
Logged: couldn't parse setting 'not-a-number'
Caller decided to fall back to a default of 0.
raise —
instead of swallowing it silently or replacing it with a new one.
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.
raise SomeError("message")triggers an exception on purpose, with your own message.- A raised exception can be caught with
try/exceptexactly like a built-in one. - A bare
raiseinsideexceptre-raises the same exception after reacting to it.
5. Custom exception classes
- 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 ofclass, just for exceptions. - Catching a custom exception type is far more precise than catching a generic
Exception.
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:
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)
Withdrawal failed: Cannot withdraw $250 from a $100 balance
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:
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.")
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.
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.
- 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
Exceptionrisks swallowing unrelated bugs too.
6. Real-world exception handling in production
- 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.
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):
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)
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:
def get_age(text):
try:
return int(text)
except:
print("Something went wrong.")
return None
print(get_age("25"))
print(get_age("abc"))
25
Something went wrong.
None
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.
- It hides genuine bugs — a typo'd variable name would just print "Something went wrong" forever, instead of surfacing a clear
NameErrorto fix. - It can swallow a user's Ctrl+C, making a program that refuses to stop when asked.
- It gives no information about what actually failed, unlike
except ValueError as e, which does.
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:
- Printing a clear message (as every example above does) is the simplest form of reporting, and enough for a small script.
- Real production systems typically log the error to a file or monitoring service, so a team can notice and fix recurring problems even when no one is watching the program run.
- Either way, an
exceptblock that does absolutely nothing — sometimes called "swallowing" an exception — is one of the most common real-world sources of bugs that go unnoticed for months.
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.
- 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.
- Every production API and web form validates user input with exactly this chapter's pattern —
try/exceptaround parsing, a custom exception for business rules, and a clear message back to the user. - Custom exceptions like Sub-topic 5's
InsufficientFundsErrorare everywhere in real codebases — payment systems, authentication, inventory checks — because they let calling code react to one specific failure without guessing what a generic error actually meant. - Logging instead of silently swallowing errors (Sub-topic 6) is how real engineering teams find out about bugs in software running on servers they aren't personally watching, often before a single user complains.
Points to Remember
try/exceptlets a program recover from a runtime error instead of crashing; name a specific exception type likeValueErrorrather than catching blindly.- A
trycan have multipleexceptblocks for different exception types;elseruns only on success,finallyalways runs. except ValueError as ecaptures the exception object;str(e)gives its human-readable message.raise SomeError("message")triggers an exception deliberately; a bareraiseinsideexceptre-raises the same exception after reacting to it.- A custom exception,
class SomeError(Exception): pass, gives a specific problem its own catchable name — more precise than a genericException. - A bare
except:is dangerous — it catches everything, including bugs andKeyboardInterrupt— and a caught error should always be reported, never silently swallowed.