Python Exception Handling: A Practical Guide
Learn practical Python exception handling with specific except clauses, else and finally blocks, re-raising and custom exceptions.
Python exceptions help a program report when an operation cannot continue normally. Good handling catches only errors the code can address, preserves useful context, and lets unexpected failures reach the right caller. This guide builds that pattern with practical examples.
Catch the error you know how to handle
A try block contains code that may raise an exception. An except clause names the errors the current function can handle. For example, parsing a user-entered number may raise ValueError:
def parse_quantity(text):
try:
quantity = int(text)
except ValueError:
return None
return quantityThis function handles invalid numeric text by returning None. A caller can then decide whether to ask again or display a message. The important point is that the handler covers a specific, expected input error.
Avoid a blanket except clause
Catching every exception can hide programming mistakes such as misspelled names, incorrect assumptions and unexpected failures. Instead of:
try:
result = process_record(record)
except:
return Nonecatch the specific exception you can recover from:
try:
result = int(record["quantity"])
except (KeyError, ValueError) as exc:
report_invalid_record(record, exc)Do not catch BaseException for ordinary application errors. It also includes signals such as KeyboardInterrupt and SystemExit, which most application handlers should allow to propagate.
Use else for the success path
An else block runs only when the try block completes without raising an exception. Keeping success-only work outside the try block makes it clearer which operation is expected to fail:
try:
quantity = int(text)
except ValueError:
print("Enter a whole number.")
else:
save_quantity(quantity)If save_quantity() itself raises an exception, this structure does not accidentally treat it as a bad integer.
Use finally for cleanup
A finally clause runs whether the protected operation succeeds or fails. It is useful for cleanup that must happen on either path. For files, prefer a context manager, which handles closing more clearly:
with open("learners.txt", encoding="utf-8") as file:
contents = file.read()The context manager closes the file when the block exits, including when an exception occurs. Use finally when a resource or action does not have a suitable context manager.
Re-raise when this layer cannot recover
Sometimes a function needs to record context or perform local cleanup, but it cannot decide what recovery is appropriate. A bare raise inside an exception handler re-raises the original exception with its traceback:
try:
write_report(path, rows)
except OSError:
log_write_failure(path)
raiseAvoid replacing an exception with a generic success-looking return value unless the function contract clearly says that is the intended recovery. Otherwise the caller may continue with incomplete or invalid data.
Add context while preserving the cause
When converting a low-level error into a domain-specific one, use exception chaining with raise ... from exc. The traceback then keeps the original cause:
class ImportDataError(Exception):
pass
def load_learners(path):
try:
with open(path, encoding="utf-8") as file:
return parse_rows(file)
except OSError as exc:
raise ImportDataError(f"Could not read learner file: {path}") from excA custom exception is most useful when callers can respond differently to that specific failure. Keep the hierarchy simple and derive application exceptions from Exception.
Choose the right error behavior
| Situation | Useful pattern | Why |
|---|---|---|
| Expected invalid user input | Catch a specific exception and return or ask again | The current layer knows the recovery |
| Unexpected error this function cannot fix | Let it propagate or re-raise | A higher layer may have the needed context |
| Low-level failure needs domain context | Raise a custom exception from the original | The caller gets clearer meaning and preserved cause |
| Resource must close regardless of outcome | Use a context manager or finally | Cleanup runs on normal and exceptional exits |
Common exception-handling mistakes
- Catching too broadly. It can suppress defects unrelated to the expected failure.
- Using exceptions for ordinary branching. Validate routine conditions directly when that is clearer.
- Ignoring the exception object. If you handle a failure, provide a useful message or diagnostic context.
- Returning from finally. A return in finally can replace a value or suppress an exception; keep control flow out of cleanup blocks.
- Logging and swallowing every error. Log at the layer that can make a useful decision, then re-raise when recovery belongs elsewhere.
Practice checklist
- Identify which operation can fail and which exception it raises.
- Decide whether this function can safely recover.
- Catch only the relevant exception types.
- Keep the normal success path in else when it improves clarity.
- Use context managers for resources when available.
- Preserve the original cause when converting an exception.
Try the patterns with a small CSV import exercise: handle a missing file separately from a row containing invalid numeric data, and make the caller decide whether to retry or skip that row.
For structured Python learning, visit the Python Programming course page or browse the course catalog.
Official Python reference
The Python tutorial's Errors and Exceptions chapter covers exception handling, raising, chaining, user-defined exceptions and cleanup actions.
Want a structured Java learning path?
Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.