Interview Questions: Exception Handling
Exception handling is one of the fastest ways an interviewer can tell if someone writes production-grade code or just "code that works on the happy path." This set covers why a bare except: is a red flag and what it silently swallows, the exact execution order of try/except/else/finally and what each part is actually for, when a custom exception class earns its keep over a built-in one, the EAFP-vs-LBYL philosophy that shapes idiomatic Python, the difference between raise and raise ... from, the surprising behavior of an exception raised inside finally, why catching Exception broadly can hide real bugs, and how custom exceptions with extra attributes carry more debugging context than a plain string message.
1 Why is a bare except: considered bad practice, and what does it actually catch?
A bare except: (with no exception type named at all) catches every exception that inherits from Python's root BaseException class — not just ordinary errors like ValueError or KeyError, but also KeyboardInterrupt (raised when a user hits Ctrl+C) and SystemExit (raised by sys.exit()). That means a bare except: can silently swallow a user's attempt to kill a hung program, or absorb a deliberate, intentional program exit and keep running anyway — both surprising and hard to debug. It also catches genuine programming mistakes, like a NameError from a typo'd variable, hiding them behind whatever fallback behavior the except block has instead of surfacing the bug. The fix is almost always to name the specific exception type(s) actually expected (except ValueError:, or except (ValueError, TypeError):) so only the anticipated failure gets caught and everything else still surfaces normally.
Treating bare except: as just a shorter way to write except Exception:, without knowing it also catches KeyboardInterrupt/SystemExit which except Exception: deliberately does not.
"Does except Exception: also catch KeyboardInterrupt?" (No — KeyboardInterrupt and SystemExit inherit directly from BaseException, not from Exception, specifically so that catching Exception doesn't accidentally block a user's Ctrl+C or a deliberate exit; only a genuinely bare except: reaches that far up the hierarchy.)
2 Walk through the execution order of try/except/else/finally — what is each part actually for?
The try block runs first. If it raises an exception, Python checks the except clauses in order and runs the first one whose type matches; if it doesn't raise anything, the else block runs instead — else exists specifically for code that should only run when the try block succeeded, keeping it visibly separate from the risky code itself (so a bug inside the success-path code doesn't accidentally get caught by an except meant for the try block). The finally block runs last, no matter what happened above it — whether the try succeeded, an exception was caught, or an exception was never caught at all and is about to propagate up. finally exists for cleanup that has to happen regardless of outcome, like closing a resource.
Putting success-path code directly inside try instead of else (which risks that code's own bugs getting silently caught by an except meant for something else), or believing finally gets skipped if an exception was never caught.
"If the try block raises an exception that no except clause matches, does finally still run?" (Yes — finally always runs before the unmatched exception propagates further up the call stack; it's the one block guaranteed to execute regardless of what happened.)
3 When does a custom exception class earn its keep over just raising a built-in one like ValueError?
A custom exception is worth defining when calling code needs to tell this specific kind of failure apart from every other reason a built-in exception might get raised. Raising a plain ValueError for "insufficient funds" means catching code that wants to react specifically to that case has to either catch every ValueError in that block (including unrelated ones from something else entirely) or inspect the error message as a string, which is fragile and breaks the moment the wording changes. A custom exception like InsufficientFundsError(Exception) gives calling code an exact type to catch with except InsufficientFundsError:, can carry extra structured data as attributes (the attempted amount, the actual balance) instead of cramming everything into a message string, and documents intent — the exception's very name explains what went wrong. It's not worth it for a one-off internal check with no real distinct failure mode; reaching for a built-in like ValueError or TypeError is completely fine when nothing downstream needs to distinguish that failure from similar ones.
Defining a custom exception for literally every possible failure regardless of whether anything downstream needs to distinguish it, or the opposite: always reaching for a generic ValueError/Exception even when a caller genuinely needs to react differently to one specific failure mode.
"If a function can fail for three completely different domain reasons that calling code needs to handle differently, is one shared exception class or three separate ones the better design?" (Three separate custom exception classes — that lets calling code write a distinct except clause per failure mode, rather than one that has to inspect the message string or an extra attribute just to figure out which of three things actually happened.)
4 What is EAFP, and how does it differ from the LBYL style?
EAFP stands for "Easier to Ask Forgiveness than Permission" — the idiomatic Python style of just attempting an operation inside a try block and handling the specific exception if it fails, rather than checking every precondition up front. LBYL, "Look Before You Leap," is the opposite style: checking conditions first (if key in dictionary: before accessing it, if os.path.exists(path): before opening a file) and only proceeding if every check passes. Python leans EAFP for a concrete reason: an upfront check and the later operation can get out of sync in a way that isn't the programmer's fault — a file can exist at check time and be deleted a moment later by something else entirely (a classic race condition), so LBYL's check doesn't actually guarantee the later operation succeeds anyway. EAFP also often reads as fewer lines and avoids a redundant check-then-do-it-anyway double cost, though it isn't automatically "more correct" for every single case — it's the accepted default in idiomatic Python specifically because of how well it handles this race-condition class of bug.
Treating EAFP as "just don't validate anything and hope for the best," or being unable to name the race-condition scenario (a check passing, then the underlying thing changing before the real operation runs) that's the actual reason EAFP is preferred over LBYL in Python.
Follow-up"Give a concrete example of an LBYL check that could still fail even though it passed." (Checking if os.path.exists(path): and then opening the file right after — between the check and the open, another process could delete that exact file, so the LBYL check passing doesn't guarantee the subsequent operation will actually succeed; wrapping the open itself in a try/except FileNotFoundError handles that gap correctly.)
5 What's the difference between raise SomeError("message") and raise SomeError("message") from original_error?
A plain raise SomeError("message") inside an except block raises a brand-new exception with no explicit, documented link back to whatever exception was originally being handled (Python does still attach it implicitly as __context__, but that's meant as incidental debugging trail, not a deliberate signal). raise SomeError("message") from original_error explicitly sets that new exception's __cause__ attribute to original_error, which is a deliberate way of saying "this new exception happened because of that other one" — and Python's default traceback printing reflects that intent, showing both exceptions chained together with a clear "the above exception was the direct cause of the following exception" message. This matters most when re-raising a different, more meaningful exception type in response to catching a lower-level one — e.g. catching a built-in ValueError from a failed float() conversion and re-raising it as a project's own custom InvalidAmountError: using from keeps the original technical failure visible in the traceback for debugging, instead of making it look like the InvalidAmountError came out of nowhere.
Believing raise ... from changes what gets caught by an except clause (it doesn't — it only affects the exception's __cause__ attribute and how the traceback is displayed, not the actual matching/catching behavior).
"After raise RuntimeError('wrapped') from e, if that RuntimeError is later caught, how would code retrieve the original exception e?" (Through the caught exception's __cause__ attribute — e.g. except RuntimeError as new_err: original = new_err.__cause__ — since from explicitly stores it there.)
6 What happens if an exception is raised inside a finally block, while a different exception is already being handled?
The new exception raised inside finally completely replaces the original one — the original exception is discarded (though it's still reachable via the new exception's __context__ attribute for debugging), and only the new exception from finally propagates further up the call stack. This is a genuinely surprising, easy-to-miss gotcha: a try block can raise a very specific, meaningful exception, but if the matching finally block also raises (say, a cleanup step that itself fails), whatever called this code only ever sees the finally block's exception, with the original one silently gone from the normal flow of control. The practical lesson is to keep finally blocks simple and defensive — ideally not doing anything that can itself raise — specifically so it never accidentally masks a more meaningful exception from the try/except above it.
Assuming both exceptions somehow propagate together, or that the original exception "wins" by being first — in reality, whichever exception is active at the very end of finally is the only one that continues propagating.
"A try block raises ValueError('original'), and its finally block raises TypeError('cleanup failed'). What exception type does the caller actually see?" (TypeError — the finally block's exception replaces the original ValueError entirely; the caller never sees the ValueError unless it goes digging through the TypeError's __context__ attribute.)
7 Why can catching Exception broadly hide real bugs, even though it's much narrower than a bare except:?
except Exception: is safer than a bare except: (it doesn't swallow KeyboardInterrupt/SystemExit), but it still catches every ordinary error — a genuine, unexpected programming bug like a TypeError from passing the wrong argument type, or an AttributeError from a typo'd method name, gets caught by the same broad clause meant to handle one specific, anticipated failure. That means a real bug can get silently absorbed by error-handling logic written for a completely different situation, and the program limps along with a misleading fallback instead of surfacing the actual mistake clearly (with a real traceback) during development. The safer default is to name the specific exception type(s) actually expected from that particular block of code, reserving a broad except Exception: for genuine last-resort boundaries (like a top-level request handler in a web server that must never crash the whole process) where it's a deliberate, considered choice rather than a reflex.
Reaching for except Exception: as a default habit on every try block regardless of what's actually expected to fail, rather than naming the specific exception type(s) the code is actually prepared to handle.
"A function does try: result = data[key] / divisor except Exception: return None. If divisor is accidentally passed in as a string instead of a number, what happens?" (The resulting TypeError from dividing by a string gets silently caught by the same broad except Exception:, and the function just returns None — masking a real type-mismatch bug as if it were the same kind of failure as a missing dictionary key.)
8 How does a custom exception with extra attributes carry more debugging context than a plain error message?
A plain exception raised with just a string message (raise ValueError("insufficient funds")) only gives calling code one thing to work with: the text itself, which is meant for humans to read, not for code to parse and act on programmatically. A custom exception class can store the actual structured data behind the failure as real attributes in its __init__ — e.g. InsufficientFundsError storing self.amount (what was requested) and self.balance (what was actually available) — while still calling super().__init__(...) with a readable message for anyone just printing or logging the exception normally. That means code catching the exception can do more than display a message: it can log the exact numbers involved, decide programmatically how far over the limit the request was, or build a custom user-facing message using the real values, all without resorting to fragile string-parsing of an error message that was never meant to be machine-readable in the first place.
Building every custom exception with only a message and no extra attributes, then having catching code awkwardly parse that message string (e.g. with regex or string-splitting) to recover values that could have just been stored as attributes directly.
Follow-up"Given except InsufficientFundsError as e:, how would code access the specific balance that caused the failure, assuming the class stores it as self.balance?" (e.balance — the caught exception object e exposes whatever attributes its __init__ assigned to self, directly accessible without parsing anything.)
9 If multiple except clauses follow one try block, does their order matter?
Yes, significantly — Python checks except clauses top to bottom and runs the first one whose type matches (or is a parent class of) the raised exception, then stops checking entirely. If a broader exception type is listed before a more specific one that's actually a subclass of it — say except Exception: listed before except ValueError: — the specific ValueError clause becomes unreachable dead code, since the broader Exception clause above it will always match first and Python never even looks further down. The correct order is always most specific exception types first, broader/more general ones last, so each clause actually gets a chance to run for the cases it's meant to handle.
Assuming Python picks the "best" or "most specific" matching except clause automatically regardless of order — it doesn't; it strictly takes the first match reading top to bottom.
"A block has except Exception: first, then except ValueError: below it. If a ValueError is raised in the try, which clause runs?" (The first one, except Exception: — since ValueError is a subclass of Exception, it matches the broader clause immediately, and the more specific except ValueError: below it never even gets checked.)
10 Does a custom exception class need to subclass Exception directly, or can it subclass another custom exception?
It can do either, and building a small hierarchy of custom exceptions is a genuinely useful pattern — a base exception like class AppError(Exception): pass that more specific exceptions subclass, e.g. class ValidationError(AppError): pass and class AuthError(AppError): pass. The payoff is that calling code can choose how broadly or narrowly to catch: except ValidationError: catches only that one specific case, while except AppError: catches any exception from that whole family (validation errors, auth errors, and anything else that subclasses AppError) in one place, which is useful at a boundary that just needs to know "something from my own application's domain went wrong" without caring exactly which kind. This is the same subclass-matching behavior except always uses (a subclass instance matches an except clause naming any of its parent classes) — it isn't special-cased for custom exceptions, it's just how Python's exception matching already works applied to your own class hierarchy.
Believing every custom exception must subclass Exception directly with no intermediate hierarchy, missing the chance to group related custom exceptions under one shared base class for easier broad-catching at a boundary.
"Given class AppError(Exception): pass and class ValidationError(AppError): pass, does except AppError: catch a raised ValidationError?" (Yes — ValidationError is a subclass of AppError, and except matches on "is this exception an instance of this type or any of its subclasses," so except AppError: catches both a plain AppError and any more specific subclass of it, including ValidationError.)
11 What's the practical difference between catching an exception as except ValueError: versus except ValueError as e:?
Both catch exactly the same exception — the as e part doesn't change what gets caught at all, only whether the caught exception object itself is made available inside the except block, bound to the name e. Without as e, the block knows that a ValueError happened but has no way to inspect it further — no access to its message via str(e), no access to any custom attributes a custom exception class might carry. With as e, the block can call str(e) to get the human-readable message, access any extra attributes the exception stores, or re-raise it (possibly wrapped in a different exception via raise ... from e). Skipping as e is fine when the block genuinely doesn't need any detail about the failure beyond knowing it happened (e.g. just printing a fixed fallback message), but it becomes limiting the moment the handling logic needs to reference specifics about what actually went wrong.
Believing as e changes which exceptions get caught, or not knowing that leaving it off entirely just means the block has no reference to the exception object at all.
"Inside except InsufficientFundsError as e:, if the class's __init__ stored self.balance = balance, how would the handler print that specific balance?" (print(e.balance) — e is the actual caught exception instance, so any attribute its __init__ assigned to self is directly reachable off e.)
12 If a try block contains a return statement, does the matching finally block still run before the function actually returns?
Yes — finally's whole purpose is to run no matter how the try/except above it is exited, and a return statement is no exception to that rule. If a try block hits return some_value, Python still runs the finally block in full before the function actually hands control back to its caller; the return doesn't skip past it. This is exactly why finally is the reliable place for cleanup code (releasing a resource, logging that an operation finished) that has to happen regardless of which of several possible return statements inside a function actually fired, or whether the function exited normally versus via an uncaught exception.
Assuming a return inside try exits the function immediately and skips finally entirely — it doesn't; finally is genuinely unskippable short of the whole process being killed.
"If finally itself also contains a return statement, which value does the function actually return — the one from try, or the one from finally?" (The one from finally — a return inside finally overrides any pending return from the try/except above it, which is exactly why deliberately returning from inside finally is generally considered confusing and avoided in practice.)
13 Why would a function re-raise a caught exception with a bare raise (no exception object after it) instead of just letting the exception propagate on its own?
A bare raise inside an except block re-raises the exact exception currently being handled, with its original traceback fully intact — useful when a block needs to do something in response to an exception (log it, run some cleanup, check a condition) but ultimately still wants the original failure to propagate up unchanged, rather than being swallowed or replaced. The alternative of not catching it at all would skip whatever the block needed to do first; the alternative of raising a brand-new exception object would lose the original one's specific type and traceback unless raise ... from is used deliberately to link them. A bare raise says "I looked at this, possibly reacted to it, but I'm not the one who should actually handle it — let it keep going exactly as it was."
Confusing a bare raise (re-raises the exception currently being handled) with raise Exception() (raises a brand-new, generic exception with no connection to whatever was just caught), or not knowing a bare raise only works meaningfully inside an except block that's actively handling something.
"Inside except ValueError as e:, what's the difference between just writing raise and writing raise e?" (Functionally very similar — both re-raise the same exception object — but a bare raise is the idiomatic form since it makes the traceback clearly show the original raise point, while raise e can, in some cases, make it look like the exception originated from that raise e line instead of its true original location.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.