A UPI payment app asks for ₹500 to be sent. The bank's server is down, or the balance is ₹300, or the PIN is wrong. Each of these is a different problem, and the app needs to react differently: retry, show "insufficient balance", or ask for the PIN again. It must never just crash. Python exceptions are how a program signals that something went wrong, and how other parts of the program catch the signal and respond.
You've met try and except already for bad input and missing files. This lesson goes further: how exceptions travel through functions, the full try/except/else/finally form, how to raise your own errors with raise, how to write custom exceptions, and habits that keep errors from hiding bugs.
What you need first: Python error messages and tracebacks, Python file handling and Python classes and objects (for custom exceptions).
Key terms
- Exception: an object Python creates when something goes wrong while the program runs, such as
ValueErrororKeyError. - Raise: create an exception and stop normal execution. Python raises them for you; you can also raise them with the
raisekeyword. - Catch (handle): deal with an exception in an
exceptblock so the program can carry on. - Traceback: the report Python prints when an exception isn't caught, showing where it happened.
- Exception hierarchy: the family tree of exception classes. Catching a parent class also catches its children.
- Custom exception: your own exception class, made by inheriting from
Exception.
How exceptions travel
When an exception happens inside a function and nothing there catches it, Python leaves that function and passes the exception to the code that called it, then to that code's caller, and so on. If it reaches the top without being caught, the program stops and prints a traceback.
def read_marks(text):
return int(text)
def average(values):
numbers = [read_marks(v) for v in values]
return sum(numbers) / len(numbers)
try:
print(average(["72", "88", "absent"]))
except ValueError as e:
print("Could not calculate:", e)
Could not calculate: invalid literal for int() with base 10: 'absent'
int("absent") failed inside read_marks. Neither read_marks nor average caught it, so it travelled up to the try block, which did. This is useful: low-level functions can just report problems, and the code that knows what to do about them handles them.
except ValueError as e stores the exception object in e. Printing it gives the error message.
The full try statement
try can have four parts:
def load_price(text):
try:
price = float(text)
except ValueError:
print(f"'{text}' is not a number")
return None
else:
print("Converted fine")
return price
finally:
print("Finished checking", repr(text))
print(load_price("499.50"))
print(load_price("free"))
Converted fine
Finished checking '499.50'
499.5
'free' is not a number
Finished checking 'free'
None
| Block | Runs when |
|---|---|
try | Always, first. Put only the code that might fail here |
except | An exception of a matching type happened in try |
else | No exception happened in try |
finally | Always, last, whether there was an exception or not, even after return |
Why else instead of putting the code at the end of try? Code in else isn't protected by the except. If it fails, you see the real error instead of it being mistaken for the error you meant to catch. Keep try blocks small.
finally is for clean-up that must happen no matter what: closing a file or a database connection, releasing a lock. In practice, with statements handle most clean-up for you, so you'll write finally less often than you might think.
Catching several exceptions
Different errors often need different responses. Use several except blocks; Python checks them top to bottom and runs the first match:
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Can't divide by zero"
except TypeError:
return "Both values must be numbers"
print(safe_divide(10, 4))
print(safe_divide(10, 0))
print(safe_divide(10, "2"))
2.5
Can't divide by zero
Both values must be numbers
To handle several types the same way, put them in a tuple:
settings = {"theme": "dark"}
for key in ["theme", "font_size"]:
try:
value = int(settings[key])
except (KeyError, ValueError) as e:
print(f"{key}: using default ({type(e).__name__})")
else:
print(key, value)
theme: using default (ValueError)
font_size: using default (KeyError)
type(e).__name__ gives the exception's class name, which is handy in messages and logs.
The exception hierarchy
Exceptions are classes arranged in a family tree. Part of it:
BaseException
├── KeyboardInterrupt (Ctrl+C)
├── SystemExit (sys.exit())
└── Exception
├── ArithmeticError
│ └── ZeroDivisionError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── OSError
│ ├── FileNotFoundError
│ └── PermissionError
├── TypeError
└── ValueError
Catching a parent catches all its children. except LookupError catches both IndexError and KeyError. You can check the family with issubclass:
print(issubclass(KeyError, LookupError))
print(issubclass(FileNotFoundError, OSError))
print(issubclass(ValueError, LookupError))
True
True
False
Two rules follow from this:
- Put specific exceptions before general ones. If
except Exceptioncomes first, the more specific blocks below it never run. - Never use a bare
except:. It catches everything, includingKeyboardInterrupt, so the user can't even stop your program withCtrl+C. If you truly need a catch-all, writeexcept Exception as e:and at least loge.
Raising your own exceptions with raise
Python raises exceptions when its own operations fail. Your functions should raise them too, when they're given something they can't work with:
def withdraw(balance, amount):
if amount <= 0:
raise ValueError(f"Amount must be positive, got {amount}")
if amount > balance:
raise ValueError(f"Insufficient balance: have ₹{balance}, need ₹{amount}")
return balance - amount
print(withdraw(1000, 300))
try:
withdraw(1000, 5000)
except ValueError as e:
print("Payment failed:", e)
700
Payment failed: Insufficient balance: have ₹1000, need ₹5000
Why raise instead of returning something like -1 or "error"? Because a return value can be ignored by accident, and the bad value then travels on and causes a confusing error far away. An exception can't be ignored: either someone handles it, or the program stops and tells you exactly where.
Pick the built-in exception that fits:
| Situation | Raise |
|---|---|
| Right type, bad value (negative age, empty name) | ValueError |
| Wrong type (a list where a number was needed) | TypeError |
| A key or item that should exist doesn't | KeyError or LookupError |
| A feature you haven't written yet | NotImplementedError |
Custom exceptions
When your program has its own kinds of failure, define your own exception classes. Callers can then catch exactly your errors and nothing else:
class PaymentError(Exception):
"""Base class for payment problems."""
class InsufficientBalanceError(PaymentError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Need ₹{amount}, but balance is ₹{balance}")
class InvalidPinError(PaymentError):
pass
def pay(balance, amount, pin):
if pin != "4821":
raise InvalidPinError("Wrong UPI PIN")
if amount > balance:
raise InsufficientBalanceError(balance, amount)
return balance - amount
for amount, pin in [(200, "4821"), (200, "0000"), (900, "4821")]:
try:
print("New balance:", pay(500, amount, pin))
except InsufficientBalanceError as e:
print("Top up needed:", e, "| short by", e.amount - e.balance)
except PaymentError as e:
print("Payment failed:", e)
New balance: 300
Payment failed: Wrong UPI PIN
Top up needed: Need ₹900, but balance is ₹500 | short by 400
The pattern to copy:
- One base class for your program (
PaymentError), inheriting fromException. - Specific classes that inherit from the base.
passis enough for the body when you only need a new name. - Extra information stored as attributes, like
e.amount, so handlers can use it. - Names that end in
Error, as Python's own exceptions do.
except PaymentError catches every payment problem; except InsufficientBalanceError catches only that one.
Re-raising and chaining exceptions
Sometimes you want to do something with an error, such as log it, and then let it carry on upwards. A bare raise inside except re-raises the same exception:
def parse_age(text):
try:
return int(text)
except ValueError:
print(f"Log: bad age value {text!r}")
raise
try:
parse_age("twenty")
except ValueError as e:
print("Caller saw:", e)
Log: bad age value 'twenty'
Caller saw: invalid literal for int() with base 10: 'twenty'
To turn a low-level error into one that makes sense for your program, raise a new exception from the original. The traceback then shows both, so no detail is lost:
class ConfigError(Exception):
pass
def read_port(settings):
try:
return int(settings["port"])
except (KeyError, ValueError) as e:
raise ConfigError("Setting 'port' is missing or not a number") from e
try:
read_port({"host": "localhost"})
except ConfigError as e:
print(e)
print("Caused by:", repr(e.__cause__))
Setting 'port' is missing or not a number
Caused by: KeyError('port')
Ask forgiveness or look before you leap?
There are two styles of handling problems:
stock = {"pen": 10}
# Look before you leap (LBYL): check first
if "pencil" in stock:
print(stock["pencil"])
else:
print("Not stocked")
# Easier to ask forgiveness than permission (EAFP): try it, handle failure
try:
print(stock["pencil"])
except KeyError:
print("Not stocked")
Not stocked
Not stocked
Python code often prefers EAFP, especially for files: checking that a file exists and then opening it can still fail if the file is deleted in between. For simple dictionary lookups, stock.get("pencil") is clearer than either.
Good error-handling habits
- Catch only what you expect and can do something about. Let other exceptions crash loudly during development, so you find the bug.
- Never swallow errors silently with
except: pass. At least log them. - Keep
tryblocks small, around the one or two lines that can fail. - Raise early when a function gets bad input, with a message that says what was wrong and what was expected.
- Use
withfor files and connections instead of manualfinallyclean-up.
Where this is used
- Web apps and APIs: frameworks catch your exceptions and turn them into error pages or HTTP status codes like 400 and 404.
- Data pipelines: bad rows raise exceptions that are caught, logged and skipped, so one broken row doesn't stop a job of 10 lakh rows.
- Libraries: requests raises
requests.exceptions.Timeout, pandas raisesKeyErrorfor a missing column. Knowing the hierarchy tells you what to catch.
Common mistakes
- Bare
except:that hides bugs and blocksCtrl+C. except Exceptionbefore specific exceptions, which makes the specific ones unreachable.- Huge
tryblocks that catch errors from lines you didn't mean to protect. - Returning error codes like
-1instead of raising. - Losing the original error by raising a new one without
from e.
Practice
- What does this print?
try:
print("A")
x = 1 / 0
print("B")
except ZeroDivisionError:
print("C")
else:
print("D")
finally:
print("E")
Show the answer
A
C
E
The error happens on the second line of try, so B is skipped. except runs, so else doesn't. finally always runs.
- Write
get_item(items, index)that returns the item, or the string "No such item" for an index that's out of range.
Show the answer
def get_item(items, index):
try:
return items[index]
except IndexError:
return "No such item"
print(get_item(["tea", "coffee"], 1))
print(get_item(["tea", "coffee"], 5))
coffee
No such item
- Write
set_age(age)that raisesTypeErrorifageisn't anint, andValueErrorif it's below 0 or above 120. Test it on 25, -3 and "25".
Show the answer
def set_age(age):
if not isinstance(age, int):
raise TypeError(f"age must be an int, got {type(age).__name__}")
if not 0 <= age <= 120:
raise ValueError(f"age must be between 0 and 120, got {age}")
return age
for value in [25, -3, "25"]:
try:
print("OK:", set_age(value))
except (TypeError, ValueError) as e:
print(type(e).__name__, "-", e)
OK: 25
ValueError - age must be between 0 and 120, got -3
TypeError - age must be an int, got str
- Create a custom exception
OutOfStockErrorthat stores the item name. Writebuy(stock, item)that raises it when the item's stock is 0, and catch it.
Show the answer
class OutOfStockError(Exception):
def __init__(self, item):
self.item = item
super().__init__(f"{item} is out of stock")
def buy(stock, item):
if stock.get(item, 0) == 0:
raise OutOfStockError(item)
stock[item] -= 1
return stock[item]
stock = {"pen": 1, "eraser": 0}
for item in ["pen", "pen", "eraser"]:
try:
print(f"Bought {item}, {buy(stock, item)} left")
except OutOfStockError as e:
print("Sorry:", e)
Bought pen, 0 left
Sorry: pen is out of stock
Sorry: eraser is out of stock
- What's wrong with this code?
try:
total = sum(prices) / len(prices)
except Exception:
print("Something went wrong")
except ZeroDivisionError:
print("No prices")
Show the answer
except Exception comes first and catches everything, including ZeroDivisionError, so the second block can never run. Swap the order so the specific exception comes first. Also consider whether catching every Exception is wise: a NameError from a typo would be hidden behind "Something went wrong".
Interview questions
What is the difference between else and finally in a try statement?
else runs only if the try block raised no exception. finally always runs, whether an exception happened, was caught or not, and even if the block returned. finally is for clean-up; else is for code that should run only on success.
Why shouldn't you use a bare except?
It catches every exception, including KeyboardInterrupt and SystemExit, so it can stop the user from interrupting the program and can hide real bugs. Catch specific exceptions, or Exception at most, and log what you catch.
How do you create a custom exception in Python?
Define a class that inherits from Exception (or from your own base exception), for example class PaymentError(Exception): pass. Add an __init__ that calls super().__init__(message) if you want to store extra attributes.
What does raise ... from e do?
It raises a new exception and records the original one as its __cause__. The traceback shows both, with the message "The above exception was the direct cause of the following exception", so the root cause isn't lost.
Key takeaways
- Uncaught exceptions travel up through callers until something handles them or the program stops.
tryruns risky code,excepthandles errors,elseruns on success andfinallyalways runs.- Catch specific exceptions, specific before general; never use a bare
except:. - Use
raisewith a clear message when a function gets input it can't handle. - Custom exceptions inherit from
Exception; use one base class for your program and specific subclasses. - Use
raisealone to re-raise, andraise NewError(...) from eto keep the original cause.
Frequently asked questions
What is the difference between an error and an exception in Python?
In everyday speech they mean the same thing. Technically, a syntax error stops the code from running at all, while exceptions happen while the code runs and can be caught with try/except. All of Python's run-time errors are exception classes.
Can I catch an exception and continue a loop?
Yes. Put the try/except inside the loop body. When an item fails, the except block runs and the loop moves on to the next item, often with continue.
How do I see the full traceback of an exception I caught?
Use traceback.print_exc() from the traceback module inside the except block, or logging.exception("message"), which logs the message with the full traceback.
What to learn next
- Work with files and folders properly in Python pathlib.
- Record errors instead of printing them with Python logging for beginners.
- Revise reading tracebacks in Python error messages explained.