Python Exception Handling Explained — try, except, finally and Real-World Patterns
Python exception handling demystified: learn try, except, else, finally with real-world examples, common mistakes, and patterns senior devs actually use..
20+ years shipping production Python across data and backend systems. Written from production experience, not tutorials.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- Try/except guards risky operations; except blocks catch specific exception types by matching class hierarchy.
- else runs only on success; finally always runs for cleanup — even after return or exception.
- Custom exceptions inherit from Exception and carry structured data like error codes and retry flags.
- Bare except: catches BaseException including KeyboardInterrupt — always use except Exception unless you have a reason.
- Caught exception overhead is ~0.5 µs in CPython; raising is cheap but exception objects are heap-allocated so don't use exceptions for normal flow.
Python exception handling is the mechanism for responding to runtime errors without crashing your program. It exists because production code encounters the unexpected—network timeouts, missing files, malformed data—and you need to decide how to recover, retry, or fail gracefully.
The try/except/finally block lets you intercept exceptions at specific points, execute cleanup logic regardless of outcome, and propagate errors up the call stack when you can't handle them locally. Under the hood, Python's interpreter maintains a per-thread exception stack; when an exception is raised, it unwinds frames until it finds a matching except clause or reaches the top-level handler, which terminates the process by default.
In the ecosystem, exception handling competes with error-return-value patterns (like Go's (result, error) tuples) and monadic approaches (like Rust's Result type). Python chose exceptions because they're non-invasive—you don't pollute every function signature with error types—but this freedom requires discipline.
The senior developer pattern is to catch exceptions at the right abstraction boundary: low-level code raises specific exceptions (e.g., ConnectionTimeout), middleware translates them into domain exceptions (e.g., PaymentGatewayDown), and top-level handlers log and return HTTP 500s or user-facing error messages. Context managers (with blocks) and raise ... from for exception chaining are the tools that keep tracebacks readable and resource leaks impossible.
The critical anti-pattern is catching Exception (or worse, bare except:) at the wrong level. This swallows KeyboardInterrupt, SystemExit, and bugs you need to see. The rule: only catch exceptions you can actually handle—retry transient failures, log and re-raise everything else.
In async code, unhandled exceptions in tasks are silently dropped unless you explicitly await or with gather()return_exceptions=True. Senior engineers watch for this because a background task that silently dies can corrupt state or leave resources locked for hours.
The real power of Python's exception system isn't preventing crashes—it's making crashes predictable, auditable, and recoverable.
Imagine you're following a recipe and step 4 says 'add eggs' — but you open the fridge and there are no eggs. Without a backup plan, you'd just stand there frozen. Exception handling is your backup plan: it says 'if step 4 fails, do THIS instead, then keep going.' Python uses the same idea — when something goes wrong at runtime, you catch the problem, handle it gracefully, and prevent your whole program from crashing.
Every program that talks to the outside world — reading files, calling APIs, querying databases — is making a bet that things will go smoothly. Spoiler: they won't. Files get deleted, networks drop, users type letters where numbers belong. Without a strategy for these moments, your program crashes and leaves users staring at a traceback they don't understand. Exception handling is how professional Python code stays alive under pressure.
The problem isn't that errors happen — it's that unhandled errors are brutal. They expose implementation details, lose in-progress work, and destroy user trust. Python's exception system gives you a structured way to anticipate failure, respond intelligently, and clean up after yourself no matter what happened. The difference between amateur and professional Python code is often just how gracefully it fails.
By the end of this article you'll know exactly how try/except/else/finally fit together, how to write custom exceptions for your own projects, when to catch broadly vs. narrowly, and the real-world patterns that show up in production codebases. You'll also know the mistakes that trip up 80% of intermediate developers — so you can skip them entirely.
What Python Exception Handling Actually Does
Exception handling in Python is a structured mechanism to intercept and respond to runtime errors without crashing the process. The core mechanic is the try block, which marks code that may raise an exception, paired with except blocks that catch specific exception types. When an exception occurs, Python unwinds the call stack until it finds a matching except handler; if none exists, the interpreter terminates with a traceback.
In practice, try/except works like a conditional branch for error paths. You can chain multiple except clauses for different exception types (e.g., ValueError, KeyError), and the first matching handler executes. The finally block runs unconditionally — even if an exception is raised or a return statement is hit — making it the correct place for cleanup like closing file handles or releasing locks. Python’s exception hierarchy (BaseException → Exception → specific types) lets you catch broadly or narrowly.
Use exception handling when an operation can fail in ways you can anticipate and recover from: parsing user input, network calls, file I/O. It is not for flow control — avoid catching generic Exception to hide bugs. In production systems, unhandled exceptions crash workers (e.g., a Gunicorn worker dies, dropping in-flight requests), while overly broad catches mask logic errors that silently corrupt data.
How Python's try/except Block Actually Works Under the Hood
When Python enters a try block, it doesn't just cross its fingers — it sets up a small safety net. If any line inside that block raises an exception, Python immediately stops executing the rest of the try block and jumps to the matching except clause. If no exception is raised, the except clause is skipped entirely.
The key word is 'matching.' Python checks each except clause top-to-bottom, looking for a clause whose exception type matches the raised exception (or is a parent class of it). This means ORDER MATTERS. If you catch a broad exception like Exception before a narrow one like ValueError, the narrow one will never be reached.
The else clause is the hidden gem most developers ignore: it runs only when the try block completed without raising any exception. This lets you separate 'the risky operation' from 'what to do with a successful result' — a pattern that makes code dramatically easier to read. Think of it as: try = attempt the danger zone, except = handle the mess, else = celebrate the win, finally = clean up regardless.
def read_config_file(file_path: str) -> dict: """ Reads a JSON config file and returns its contents as a dictionary. Demonstrates try / except / else / finally working together. """ config_file = None try: # ATTEMPT: open the file — this can raise FileNotFoundError config_file = open(file_path, 'r') import json # ATTEMPT: parse JSON — this can raise json.JSONDecodeError config_data = json.load(config_file) except FileNotFoundError: # Fires ONLY when the file doesn't exist at that path print(f"[ERROR] Config file not found at: {file_path}") return {} # Return a safe default instead of crashing except json.JSONDecodeError as parse_error: # Fires ONLY when the file exists but contains invalid JSON # 'as parse_error' gives us access to the error details print(f"[ERROR] Config file has invalid JSON: {parse_error.msg}") return {} else: # Runs ONLY if the try block succeeded with zero exceptions # Perfect place for 'success path' logic — keeps it separate from error handling print(f"[OK] Config loaded successfully. Keys found: {list(config_data.keys())}") return config_data finally: # Runs ALWAYS — whether an exception happened or not # Critical for cleanup: close the file so we don't leak file handles if config_file and not config_file.closed: config_file.close() print("[CLEANUP] File handle closed.") # --- Test case 1: file exists and is valid JSON --- # Assume 'settings.json' contains: {"debug": true, "port": 8080} result = read_config_file("settings.json") print(f"Result: {result}\n") # --- Test case 2: file does not exist --- result = read_config_file("missing.json") print(f"Result: {result}")
Building Custom Exceptions That Actually Communicate Intent
Python's built-in exceptions are great for generic problems, but they're terrible communicators for domain-specific failures. When your payment service fails, raising a generic ValueError tells the caller almost nothing. A PaymentDeclinedError with a reason code and retry hint — that's information a caller can act on.
Custom exceptions are just classes that inherit from Exception (or a more specific built-in). The real power comes from adding attributes: error codes, context data, user-facing messages, or flags like is_retryable. This turns exceptions from blunt instruments into structured data packets.
The best pattern is an exception hierarchy: a base exception for your module, then specific exceptions that inherit from it. This lets callers choose their level of granularity — catch the base exception to handle everything from your module, or catch a specific subclass to handle only one scenario. This is exactly how Python's own standard library works: OSError is the parent of FileNotFoundError, PermissionError, and a dozen others.
# --- Define a custom exception hierarchy for a payment module --- class PaymentError(Exception): """ Base exception for all payment-related failures. Any caller catching PaymentError will catch all subclasses too. """ def __init__(self, message: str, transaction_id: str): # Always call super().__init__() so Python's exception machinery works correctly super().__init__(message) self.transaction_id = transaction_id # Attach useful context data class PaymentDeclinedError(PaymentError): """ Raised when the card issuer declines the charge. Carries a decline_code so the caller knows WHY — not just that it failed. """ def __init__(self, transaction_id: str, decline_code: str): message = f"Payment declined (code: {decline_code})" super().__init__(message, transaction_id) self.decline_code = decline_code self.is_retryable = False # Declined cards won't succeed on retry class PaymentGatewayTimeoutError(PaymentError): """ Raised when the payment gateway doesn't respond in time. Unlike a decline, this one IS safe to retry. """ def __init__(self, transaction_id: str, timeout_seconds: int): message = f"Gateway timed out after {timeout_seconds}s" super().__init__(message, transaction_id) self.is_retryable = True # Timeout might be temporary — caller can retry # --- Simulate a payment processing function --- def process_payment(amount: float, card_token: str, transaction_id: str) -> str: """ Attempts to charge a card. Raises specific PaymentError subclasses on failure. """ # Simulate a declined card scenario if card_token == "DECLINED_CARD": raise PaymentDeclinedError( transaction_id=transaction_id, decline_code="insufficient_funds" ) # Simulate a gateway timeout if card_token == "SLOW_GATEWAY": raise PaymentGatewayTimeoutError( transaction_id=transaction_id, timeout_seconds=30 ) return f"Success: charged ${amount:.2f}" # --- Caller code: handle each failure type differently --- def checkout(amount: float, card_token: str): transaction_id = "TXN-20240815-001" try: result = process_payment(amount, card_token, transaction_id) print(f"[PAYMENT] {result}") except PaymentDeclinedError as error: # We know exactly why it failed AND that retrying is pointless print(f"[DECLINED] Transaction {error.transaction_id} failed: {error}") print(f" Decline reason: {error.decline_code}") print(f" Retryable: {error.is_retryable}") # In real code: show user a 'check your card details' message except PaymentGatewayTimeoutError as error: # Different response — we might queue this for automatic retry print(f"[TIMEOUT] Transaction {error.transaction_id} timed out: {error}") print(f" Retryable: {error.is_retryable}") # In real code: push transaction_id onto a retry queue except PaymentError as error: # Catch-all for any other payment failure we didn't specifically handle print(f"[PAYMENT ERROR] Unexpected failure for {error.transaction_id}: {error}") print("=== Test 1: Declined card ===") checkout(99.99, "DECLINED_CARD") print("\n=== Test 2: Gateway timeout ===") checkout(49.99, "SLOW_GATEWAY") print("\n=== Test 3: Success ===") checkout(25.00, "VALID_TOKEN")
Context Managers and Exception Chaining — The Senior Developer Patterns
Two patterns separate intermediate exception handling from genuinely professional code: context managers and exception chaining.
Context managers (the with statement) are the correct way to handle any resource that needs cleanup — files, database connections, network sockets, locks. Under the hood, Python calls __exit__ on the context manager even if an exception blows up inside the with block. This replaces the try/finally pattern for resource cleanup and removes the risk of forgetting to close something.
Exception chaining solves a subtle but serious problem: what happens when your exception handler itself fails, or when you want to raise a higher-level exception but preserve the original cause? Python's 'raise NewError() from original_error' syntax chains the exceptions together, so the traceback shows both the root cause and the higher-level consequence. Without this, you lose the original traceback — and debugging becomes a nightmare. Critically, 'raise NewError() from None' explicitly suppresses the chain when the original exception would confuse rather than help the caller.
import sqlite3 from contextlib import contextmanager # --- Custom exception for our data layer --- class DatabaseError(Exception): """Raised when a database operation fails at the application level.""" pass # --- Context manager for safe database transactions --- @contextmanager def managed_transaction(db_path: str): """ A context manager that handles the full lifecycle of a database connection: - Opens the connection - Commits if the block succeeds - Rolls back if any exception occurs - Always closes the connection Usage: with managed_transaction('mydb.sqlite') as cursor: cursor.execute(...) """ connection = sqlite3.connect(db_path) cursor = connection.cursor() try: # Yield the cursor to the 'with' block — execution pauses here yield cursor # If we reach this line, the 'with' block completed without exceptions connection.commit() print("[DB] Transaction committed.") except Exception as db_exception: # Something went wrong inside the 'with' block — roll back every change connection.rollback() print(f"[DB] Transaction rolled back due to: {db_exception}") # EXCEPTION CHAINING: wrap the low-level sqlite error in our domain error. # 'raise ... from db_exception' preserves the original traceback as __cause__. # Callers see a clean DatabaseError, but the full sqlite context is still there # for debugging when they inspect the traceback. raise DatabaseError( f"Failed to complete database operation: {db_exception}" ) from db_exception finally: # Runs regardless — closes connection even if commit or rollback failed connection.close() print("[DB] Connection closed.") # --- Application-level function using the context manager --- def save_user(db_path: str, username: str, email: str) -> None: """ Saves a new user record. If anything fails, the whole transaction rolls back. """ try: with managed_transaction(db_path) as cursor: # Create table if needed (idempotent) cursor.execute(""" CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, email TEXT NOT NULL ) """) # This INSERT will fail if username already exists (UNIQUE constraint) cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) print(f"[APP] User '{username}' queued for insert.") except DatabaseError as error: # We catch our domain-level error here print(f"[APP] Could not save user: {error}") # The original sqlite3 error is still accessible at error.__cause__ print(f"[APP] Root cause: {error.__cause__}") # --- Test it --- DB_FILE = ":memory:" # In-memory SQLite — no file needed, perfect for demos print("=== Insert first user ===") save_user(DB_FILE, "alice", "alice@example.com") # Note: :memory: databases are fresh per-connection, so duplicate test # needs a persistent file. We'll simulate a constraint violation differently. print("\n=== Simulate a broken operation ===") try: with managed_transaction(DB_FILE) as cursor: cursor.execute("SELECT * FROM nonexistent_table") # This will fail except DatabaseError as error: print(f"[APP] Caught at top level: {error}")
NewError() from original' to make the chain intentional and explicit.from, you lose that link and spend hours guessing what actually broke.from preserves the root cause traceback.from None only when the original exception is an implementation detail callers shouldn't see.When NOT to Catch Exceptions — The Pattern That Protects Your Whole System
Knowing when to catch is only half the skill. Knowing when to let exceptions propagate is just as important — and most intermediate developers get this wrong.
The core rule: only catch an exception if you can actually DO something useful with it at that level. If your function can't recover from a database being down, it shouldn't catch that error — let it bubble up to the layer that can (the request handler, which can return a 503 response). Catching and re-raising without adding value is just noise.
The second rule: never use exceptions for flow control in your happy path. Some developers write try/except to check if a key exists in a dictionary instead of using 'in' or .get(). This makes code harder to read and has a performance cost on the failure branch.
The third rule: be very precise about WHAT you catch. A bare 'except:' with no exception type catches absolutely everything — including KeyboardInterrupt, SystemExit, and GeneratorExit. This can make your program impossible to stop with Ctrl+C, mask genuine bugs, and swallow signals your OS sends. It's one of the most dangerous patterns in Python.
import json from typing import Optional # --- Simulate a simplified web request/response cycle --- class HttpResponse: def __init__(self, status_code: int, body: dict): self.status_code = status_code self.body = body def __repr__(self): return f"HttpResponse({self.status_code}, {self.body})" # --- Low-level parser — only handles what it knows about --- def parse_request_body(raw_body: str) -> dict: """ Parses a JSON string into a dict. DOES NOT catch exceptions — it has no idea what to do with a parse failure. Lets json.JSONDecodeError propagate to whoever called it. """ # No try/except here — this function's job is parsing, not error handling return json.loads(raw_body) def validate_user_payload(payload: dict) -> None: """ Checks that required fields are present. Raises ValueError with a descriptive message — doesn't catch anything. """ required_fields = {"username", "email", "password"} missing = required_fields - payload.keys() if missing: # Raise with enough detail for the handler to build a useful error response raise ValueError(f"Missing required fields: {sorted(missing)}") # --- High-level handler — THIS is the right place to catch exceptions --- # It has enough context to turn failures into proper HTTP responses. def handle_register_request(raw_request_body: str) -> HttpResponse: """ Handles a user registration API request. This is the ONLY layer that should catch exceptions — because it's the only layer that knows how to turn them into HTTP responses the client understands. """ try: # Step 1: Parse — could raise json.JSONDecodeError payload = parse_request_body(raw_request_body) # Step 2: Validate — could raise ValueError validate_user_payload(payload) # Step 3: (In real code: save to DB, hash password, etc.) username = payload["username"] except json.JSONDecodeError: # We CAN handle this here: it means 400 Bad Request return HttpResponse( status_code=400, body={"error": "Request body must be valid JSON"} ) except ValueError as validation_error: # We CAN handle this here: it means 422 Unprocessable Entity return HttpResponse( status_code=422, body={"error": str(validation_error)} ) # Note: We do NOT catch Exception here. # If something unexpected blows up (DB is down, OOM), let it propagate # to the framework's top-level error handler, which will log it properly # and return a 500 without leaking stack traces to the client. else: return HttpResponse( status_code=201, body={"message": f"User '{username}' registered successfully"} ) # --- Run test cases --- print("=== Valid registration request ===") valid_body = '{"username": "bob", "email": "bob@example.com", "password": "s3cure!"}' response = handle_register_request(valid_body) print(response) print("\n=== Malformed JSON ===") response = handle_register_request("{this is not json}") print(response) print("\n=== Missing fields ===") partial_body = '{"username": "carol"}' response = handle_register_request(partial_body) print(response)
Exception Handling in Async Code — The Silent Failures Senior Engineers Watch For
Async Python (asyncio) adds a new layer of complexity to exception handling. A coroutine that raises an exception behaves differently depending on how it's run. If you await it inside a try/except, the exception is caught normally. But if a coroutine is scheduled on the event loop but never awaited — a 'fire-and-forget' pattern — the exception is silently swallowed and logged to the event loop's exception handler. You'll never see it unless you configure that handler.
Another common pitfall is exceptions inside TaskGroup or asyncio.gather(). If one task raises, the entire group is cancelled and all other running tasks get CancelledError. You need to handle that cancellation properly or you'll leak tasks and resources.
The rule for async code: always assign the result of an async operation to a variable, even if you don't need it, to ensure exceptions are surfaced. Use TaskGroup (Python 3.11+) for structured concurrency — it forces you to handle exceptions at the point of spawning.
Context managers work in async code too, via __aenter__ and __aexit__. The same finally-like cleanup guarantee applies, but you must use 'async with' and the context manager must implement the async protocol.
import asyncio import logging # Configure the event loop to log unhandled exceptions logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s') async def risky_io() -> str: """Simulates an I/O operation that fails randomly.""" await asyncio.sleep(0.1) raise ConnectionError("Database connection refused") async def safe_worker(): """Properly awaits and catches exceptions.""" try: result = await risky_io() print(f"Result: {result}") except ConnectionError as e: logging.exception(f"Worker failed with connection error: {e}") return None async def fire_and_forget_worker(): """Schedules a coroutine but never awaits it — exception is lost.""" task = asyncio.create_task(risky_io()) # Not awaited: task executes but its exception disappears into the loop's exception handler # This is almost always a bug await asyncio.sleep(0.2) # Wait long enough for the task to fail # By now, the exception has been swallowed by the event loop async def task_group_worker(): """Uses TaskGroup to ensure all exceptions are surfaced.""" try: async with asyncio.TaskGroup() as tg: task1 = tg.create_task(risky_io()) task2 = tg.create_task(risky_io()) # This will trigger cancellation of task1 except* ConnectionError as e: # Python 3.11+ exception groups allow catching multiple exceptions logging.exception(f"TaskGroup failed with {len(e.exceptions)} connection errors") async def main(): print("=== Safe worker (catches exception correctly) ===") await safe_worker() print("\n=== Fire-and-forget worker (exception lost) ===") await fire_and_forget_worker() print("[WARNING] No exception printed above — it was swallowed by the event loop.") print("\n=== TaskGroup worker (surfaces all exceptions) ===") await task_group_worker() if __name__ == "__main__": asyncio.run(main())
create_task() but never awaited is like a letter posted with no return address — you'll never know if it was delivered or not.- Python's event loop has a default exception handler that logs to stderr, but only if you set up logging early.
- If your fire-and-forget task fails, the exception is caught by the loop, logged only if you've configured
.loop.set_exception_handler() - Most developers don't configure that handler — so exceptions vanish silently.
- Use
TaskGroup(3.11+) to force exception handling at the point of task creation. - Always store a reference to the task if you need to check its result later with
.exception().
.add_done_callback() to log failures.Why Bare except Clauses Cost You Your Job
A bare except: clause catches every exception, including KeyboardInterrupt, SystemExit, and GeneratorExit. You just silently swallowed the user hitting Ctrl+C or the OS sending a termination signal. Worse, you masked the bug that would have told you your database connection pool is exhausted. Production incidents start here. When you catch everything, you debug nothing. The only acceptable catch-all is except Exception:, and even that needs a solid reason—like logging the full traceback and re-raising. If you're tempted to use bare except: for "safety," you're actually building an opaque box that will fail in mysterious ways at 3 AM. The rule: specify the exception or don't catch it.
# io.thecodeforge # Bare except — the production incident starter pack import sys try: process_payment(order_id=42, amount=-50.00) except: # Swallows KeyboardInterrupt, SystemExit, everything print("Payment failed") # Logs nothing, re-raises nothing # The correct pattern — catch only what you expect try: process_payment(order_id=42, amount=-50.00) except ValueError as e: logger.critical("Invalid payment amount: %s", e) raise # Re-raise to prevent silent corruption
except: also catches MemoryError. If your system is OOM, you just silently failed to allocate memory and kept running in a zombie state. You want the process to die fast so your orchestrator can restart it cleanly.Logging Exceptions Like You Mean It — The Traceback Is Your Evidence
in an except block is commit-level negligence. When a payment fails at 2 AM, you need the full traceback, the input state, and the server context. Use print() — it automatically includes the stack trace and respects your logging levels. Never log the exception manually with logger.exception()str(e); you lose the line number and call stack. Every minute you waste reproducing an error without a traceback is a minute your users are angry. Pattern: log the exception, log the context (user ID, request ID, order amount), then decide: re-raise, return a fallback, or swallow. But know that swallowing without logging is lying to your future self.
# io.thecodeforge # Bad — loses traceback import logging try: user = fetch_user(user_id=1001) except Exception as e: print(f"Failed: {e}") # No stack trace, no context # Correct — preserves evidence try: user = fetch_user(user_id=1001) except Exception: logger.exception("Failed to fetch user %s", 1001) raise # Let the caller handle retry logic
logger.exception() or log the traceback yourself. Print is for prototyping, not production.The Silent Retry Storm — Unhandled Exception in Celery Worker
except: (bare) but the code inside it raised a new exception (e.g., logging connection failure) which was silently suppressed by the bare except. Also, there was no logging statement inside the except block — the developer forgot to add log.exception(). The task retried indefinitely because the exception was swallowed and no failure signal sent to the broker.except Exception:. Add log.exception("Task failed due to unhandled error") inside the except block. Set max_retries on the task to prevent infinite retries. Implement a circuit breaker pattern for database-dependent tasks.- Never use bare except: in production code — always specify exception type.
- Always log exceptions at the point of capture using
which includes the full traceback.log.exception() - Set explicit retry limits on background tasks to avoid retry storms.
- Test failure scenarios: inject a mock exception to verify logging and retry behaviour.
PYTHONWARNINGS=error to turn all warnings into errors. Add raise to re-raise if unsure.raise NewError(...) without from original. Add from e to preserve the chain.except KeyboardInterrupt: raise to allow clean exit, or use except Exception: to avoid catching it.__exit__ is called and cleanup happens. Use contextlib.closing() or @contextmanager from contextlib.python -X dev script.py # Enables developer mode: shows source line references, memory dumps on crashimport traceback; traceback.print_exc() # In a repl or script to print the last traceback manuallylogging.exception() and re-raise only if necessary.grep -rn 'except:' . --include='*.py' # Find all bare except clauses in the projectpython -c "import logging; logging.basicConfig(level=logging.DEBUG); raise ValueError('test')" # Test logging setuppython -c "def f(): try: raise ValueError('original'); finally: return 'shadow'
print(f())" # See shadowpython -W error::RuntimeError # Test for unexpected behavior| Clause | When It Runs | Can Access Exception? | Typical Use Case |
|---|---|---|---|
| try | Always — it's the guarded block | N/A — exceptions are raised here | Wrap any code that might fail |
| except ExceptionType | Only when a matching exception is raised | Yes — via 'as error' | Handle specific, known failure modes |
| else | Only when try completes with NO exception | No — no exception occurred | Success-path logic, kept separate from error handling |
| finally | Always — exception or not, even after return | Only if re-raised manually | Resource cleanup: close files, DB connections, locks |
| File | Command / Code | Purpose |
|---|---|---|
| file_reader.py | def read_config_file(file_path: str) -> dict: | How Python's try/except Block Actually Works Under the Hood |
| payment_exceptions.py | class PaymentError(Exception): | Building Custom Exceptions That Actually Communicate Intent |
| database_service.py | from contextlib import contextmanager | Context Managers and Exception Chaining |
| api_handler.py | from typing import Optional | When NOT to Catch Exceptions |
| io | logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %... | Exception Handling in Async Code |
| payment_processor.py | try: | Why Bare except Clauses Cost You Your Job |
| api_handler.py | try: | Logging Exceptions Like You Mean It |
Key takeaways
Common mistakes to avoid
5 patternsCatching bare 'except:' instead of 'except Exception:'
Putting too much code inside the try block
Raising a new exception inside except without 'from', losing the original traceback
Using exceptions for normal flow control
dict.get(), 'if key in dict', or other explicit checks. Exceptions are for exceptional situations, not missing keys.Silent pass in except block
logging.warning(). In critical paths, use logging.exception() to capture the full traceback. If you truly must suppress, add a comment explaining why.Interview Questions on This Topic
What's the difference between 'except Exception' and a bare 'except:'? When would you ever use the bare form?
except: catches every subclass of BaseException, including KeyboardInterrupt, SystemExit, and GeneratorExit. except Exception catches only those that inherit from Exception — which includes all application-level errors. Bare except: should almost never be used. One valid case is in a cleanup handler that must run regardless of how the application exits (e.g., closing a hardware device), but even then you likely want to re-raise the exception after cleanup. In production, always use except Exception or more specific types.Explain exception chaining in Python. What's the difference between 'raise B() from A' and 'raise B() from None', and when would you use each?
raise B() from A sets B.__cause__ to A, and the traceback shows both exceptions explicitly linked. raise B() from None sets B.__cause__ to None, suppressing the original exception — the traceback only shows B. Use from when wrapping a low-level exception (e.g., sqlite3.Error) into a domain exception (e.g., DatabaseError) so callers can see both. Use from None when the original exception contains sensitive implementation details or would confuse the caller (e.g., when converting a JSON decode error into a HTTP 400 response). The default bare raise B() inside an except block sets B.__context__ implicitly, leading to the confusing 'During handling of the above exception' message — always prefer explicit chaining.A junior dev on your team wrapped an entire 50-line function in a single try/except block. What's wrong with that approach, and how would you refactor it?
Frequently Asked Questions
Bare 'raise' re-raises the current exception with its original traceback completely intact — the call stack looks like the exception never passed through your handler. 'raise e' (where e is the caught exception) technically re-raises the same object but resets the traceback to the current line, making it look like the exception originated in your handler. Always prefer bare 'raise' when you want to re-raise without modifying anything.
Yes, and it's a subtle trap. If a finally block contains a return statement or raises its own exception, the original exception is silently discarded. This is almost never what you want. Keep finally blocks focused exclusively on cleanup operations — no return statements, no raising new exceptions — to avoid accidentally swallowing errors.
Python's culture strongly favors EAFP — attempting the operation and handling exceptions if it fails — over LBYL, which checks preconditions before acting. EAFP is more robust in concurrent environments (a file can be deleted between your check and your open call) and is often more readable. Use LBYL sparingly, for cases where checking first is dramatically cheaper than attempting and failing.
The try block itself has near-zero overhead — about 0.01 µs per line when no exception is raised. Raising an exception is heavier: ~0.5 µs to create the exception object and unwind the stack. Actually catching and handling an exception adds ~1-2 µs depending on the handler complexity. This is fast enough that exceptions shouldn't be avoided for correctness, but don't use them in hot loops — a try/except inside a loop that never fails is fine, but a loop that fails on every iteration will be 100x slower than an if-check.
Override the __reduce__ method to return a tuple with the exception class and its constructor arguments. For even better serialization, implement __str__ and __repr__ to include all relevant attributes. If you're using structured logging (e.g., JSON logs), add a method that returns a dictionary of all relevant fields. This makes it trivial to log exceptions as structured data for analysis tools like ELK.to_dict()
20+ years shipping production Python across data and backend systems. Written from production experience, not tutorials.
That's Exception Handling. Mark it forged?
5 min read · try the examples if you haven't