Exceptions: try, except, raise
Handle expected errors gracefully and raise clear errors of your own.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
An exception is Python's way of signalling that something went wrong. try/except lets you catch the specific errors you expect and recover, while raise lets your own code report problems clearly.
Explained simply
When Python hits a problem it cannot handle, like dividing by zero or opening a file that does not exist, it stops and raises an exception. If nobody catches it, the program ends and prints a traceback: a report of where it happened and why.
Errors are normal. Users type letters where you expect numbers. Networks drop. Files go missing. Good programs expect these problems and react sensibly: show a helpful message, try again, or use a default value. That is what try and except are for.
But catching errors has a cost. If you catch everything and ignore it, real bugs hide and your program quietly does the wrong thing. The rule is: catch only the errors you expect and know how to handle. Let the surprising ones crash loudly so you can fix them.
Your own functions can raise errors too. If someone calls withdraw(-50), it is better to raise ValueError("amount must be positive") right away than to return a strange balance. A clear error at the right place saves hours of debugging later.
Press Play on a diagram to walk through it one step at a time.
- Exception
- ValueError
- TypeError
- LookupError: KeyError, IndexError
- OSError: FileNotFoundError
- ArithmeticError: ZeroDivisionError
- KeyboardInterrupt
- SystemExit
- Step 1try
Run code that might fail
- Step 2except
Runs only if a matching error was raised
- Step 3else
Runs only if try raised nothing
- Step 4finally
Always runs, for cleanup
- 1parse_amount()
float("abc") raises ValueError
- 2No handler here
Function stops, error goes to caller
- 3add_expense()
No matching except, keeps going up
- 4main()
except ValueError prints a friendly message
- 5Program continues
Or exits cleanly with an exit code
In depth
Reading a traceback like a pro
A traceback starts with "Traceback (most recent call last):" and lists the chain of function calls, oldest first. Each entry shows the file, the line number, the function name and the line of code. The last line is the most important: the exception type and its message, such as KeyError: 'email'.
Read from the bottom up. First the error type and message tell you what went wrong. Then the last frame shows where it happened. Then walk upwards until you reach a line in your own code, because frames inside libraries are usually just the messenger. Since Python 3.11, tracebacks also underline the exact part of the line that failed with ^ markers, which is very helpful in long expressions like data["user"]["email"].
If you see "During handling of the above exception, another exception occurred", there are two errors: the first one, and a second raised inside an except block.
- 1Traceback header
Most recent call last
- 2Outer frames
Where the call started, often main()
- 3Your code's frame
Usually where the bug really is
- 4Innermost frame
The line that raised, with ^ markers
- 5Type and message
Read this first: KeyError: 'email'
How except chooses a handler
When an exception is raised inside try, Python checks each except clause from top to bottom and runs the first one whose type matches. A clause matches the exception's own class or any of its parent classes. So except OSError also catches FileNotFoundError and PermissionError, because they are subclasses of OSError.
That means order matters: put specific handlers before general ones. If except Exception comes first, a later except ValueError never runs. You can catch several types at once with a tuple: except (ValueError, TypeError) as err. The as err part gives you the exception object, so you can print it or read attributes like err.filename on an OSError.
If no clause matches, the exception keeps travelling up to the caller, and then the caller's caller, until something catches it or the program ends. This is why you can handle an error far from where it was raised, at the level that knows what to do.
- Specific before general: FileNotFoundError, then OSError
- except Exception does not catch KeyboardInterrupt or SystemExit
- A bare except: catches even Ctrl+C; avoid it
else, finally and with: who cleans up
Keep the try block small: only the line that can fail. Code that should run only if it succeeded goes in else. That way, an error in the follow-up code is not accidentally caught by an except meant for the first line.
finally always runs: after success, after a handled error, and even when an unhandled error is on its way out or a return happens inside try. Use it for cleanup such as releasing a lock or deleting a temporary file. Never put return in finally, because it silently throws away any exception in flight; newer Python versions warn about it.
For most cleanup you do not need finally at all: a with-statement (context manager) does it for you. with open(...) closes the file, and with lock: releases the lock. Inside, the context manager uses the same try/finally idea.
Raising well: messages, chaining and custom types
Raise the most fitting built-in type: ValueError for a right type but bad value (age = -3), TypeError for the wrong type, KeyError or LookupError for something missing, and RuntimeError when nothing else fits. Write messages that help: include the bad value and what was expected, such as f"amount must be positive, got {amount}".
When you catch a low-level error and raise a higher-level one, chain them with raise NewError(...) from err. The traceback then shows both, with "The above exception was the direct cause of the following exception", so no information is lost. Inside an except block, a bare raise re-raises the current exception unchanged, which is useful after logging.
For your own projects, define a small family: class TrackerError(Exception), then class StorageError(TrackerError) and so on. Callers can catch TrackerError to handle all of them, or one subclass for a specific case.
- StorageError
- File missing or corrupt JSON
- ValidationError
- Negative amount, bad date
- RateApiError
- Currency API down or slow
EAFP vs LBYL: two styles of handling problems
LBYL means look before you leap: check first, then act. if key in d: value = d[key]. EAFP means easier to ask forgiveness than permission: just try it and handle the failure. try: value = d[key] except KeyError: ... Python code often prefers EAFP.
EAFP avoids race conditions. Checking if path.exists() and then opening the file can still fail, because another program may delete it between the two lines. Trying to open it and catching FileNotFoundError is always correct. EAFP also avoids doing the same lookup twice.
LBYL is better when failure is common and cheap to check, or when the action is hard to undo. For simple cases, the best answer is often neither: d.get(key, default) returns a default with no exception at all. And contextlib.suppress(FileNotFoundError) is a tidy way to say "this error is fine, ignore it".
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Read a traceback and spot the error~35m
- 2Catch specific exceptions with try/except~35m
- 3Use else and finally blocks~35m
- 4Raise errors with clear messages~35m
- 5Define a custom exception class~35m
Key points
- Read a traceback from the bottom: the last line names the error type and message.
- Catch the narrowest exception you can handle, like ValueError, not everything.
- except Exception catches its subclasses too, because the hierarchy is a tree.
- raise ValueError("clear message") when your function receives bad input.
- Custom exceptions subclass Exception and name problems in your domain.
Key terms
Tap a card to flip it. 0/5 known
Examples
class InsufficientFunds(Exception):
"""Raised when a withdrawal exceeds the balance."""
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFunds(f"Need {amount}, have {balance}")
return balance - amount
try:
new_balance = withdraw(100, int(input("Amount: ")))
except ValueError:
print("Please type a whole number.")
except InsufficientFunds as err:
print("Declined:", err)
else:
print("New balance:", new_balance)Asking for a number until the user gets it right
A program asks for an age. Step 1: put only the risky conversion inside try. Step 2: catch ValueError, the error int() raises for text like "twenty". Step 3: check the range yourself and raise or print a clear message. Step 4: loop until the input is valid. Step 5: notice Ctrl+C still stops the program, because we did not catch everything.
def ask_age() -> int:
while True:
raw = input("Your age: ")
try:
age = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number, try again.")
continue
if 0 < age < 130:
return age
print("Age must be between 1 and 129.")
print("Next year you will be", ask_age() + 1)Turning low-level errors into clear app errors
Your app loads settings from JSON. Two things can go wrong: the file is missing (FileNotFoundError) or it is broken (json.JSONDecodeError, a subclass of ValueError). Step 1: catch each one where it happens. Step 2: raise your own ConfigError with a message the user understands. Step 3: use from err so the original cause still appears in the traceback for developers. Step 4: main() catches only ConfigError and exits with a non-zero code.
import json, sys
from pathlib import Path
class ConfigError(Exception): pass
def load_config(path: Path) -> dict:
try:
return json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError as err:
raise ConfigError(f"Config file not found: {path}") from err
except json.JSONDecodeError as err:
raise ConfigError(f"{path} line {err.lineno}: invalid JSON") from err
try:
cfg = load_config(Path("config.json"))
except ConfigError as err:
sys.exit(f"Error: {err}")Quick reference
- Read tracebacks bottom up: error type and message, then the last frame in your own code
- except clauses run top to bottom; put specific types before general ones
- except (ValueError, TypeError) as err catches either type
- Keep try tiny; put follow-up code in else and cleanup in finally or a with-block
- raise AppError("message") from err keeps the original cause in the traceback
- A bare raise inside except re-raises the current exception unchanged
- d.get(key, default) and contextlib.suppress(...) avoid needless try blocks
Common mistakes
- A bare except: hides bugs and even catches Ctrl+C.
- Wrapping huge blocks in try, so you cannot tell what failed.
- Silently passing on errors instead of logging or re-raising them.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write safe_divide(a, b) that returns a / b, but returns None and prints a message when b is zero.
- Exercise 2medium
Read numbers.txt (one number per line), sum the valid ones, and report each bad line with its line number instead of crashing.
- Exercise 3hard
Create a BankError base class with InsufficientFunds and AccountLocked subclasses. InsufficientFunds should store needed and available as attributes. Show one handler for each and one that catches both.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between an error and an exception in Python?
- In everyday talk they mean the same thing. Technically, exceptions are objects raised at run time, and most built-in error types end in Error; a SyntaxError is detected when the code is compiled, before it runs.
- Should I catch Exception?
- Only at the top of a program or a long-running loop, where you log the error and keep going or exit cleanly. Deep inside your code, catch the specific types you can actually handle.
- How do I log an exception with its traceback?
- Inside an except block, call logging.exception("message"). It logs at ERROR level and adds the full traceback automatically.
- What is ExceptionGroup?
- Added in Python 3.11, it bundles several exceptions raised together, for example by concurrent tasks. You handle its members with the except* syntax.