Interview Q&A · Python · 15 questions in this topic
Exception Handling — Python Interview Q&A
try/except/else/finally, raising and chaining, the exception hierarchy, and what production logging of exceptions should look like. Part of Exception Handling · 375 questions in the Python bank.
What is the difference between an exception and an error in Python?
Answer
In Python, "error" and "exception" are largely used interchangeably, but technically Exception is a class in the BaseException hierarchy representing recoverable problems, while more severe issues (like SystemExit or KeyboardInterrupt) sit outside Exception entirely, and syntax problems (SyntaxError) are detected before your code even runs.
Almost everything you'd normally want to catch inherits from Exception (like ValueError, TypeError, KeyError). BaseException is the true root of the hierarchy, but its other direct children — SystemExit, KeyboardInterrupt, GeneratorExit — represent things you almost never want to accidentally catch, which is exactly why idiomatic code catches Exception, not BaseException.
Example
try: result = 10 / 0 except Exception as e: # catches ZeroDivisionError and most others print(f"Caught: {e}") # Caught: division by zero print(issubclass(ValueError, Exception)) # True print(issubclass(KeyboardInterrupt, Exception)) # False -- deliberately excluded
💡 Explaining why KeyboardInterrupt and SystemExit are excluded from Exception — so a broad except Exception: doesn't accidentally swallow a user's Ctrl+C or a deliberate sys.exit() — shows you understand the hierarchy's design intent, not just its shape.
How does try work in Python?
Answer
A try block wraps code that might raise an exception. If an exception occurs, Python immediately stops executing the rest of the try block and looks for a matching except clause to handle it.
Only the code inside the try block is protected — an exception raised in a function called from the try block still propagates up into it and can be caught there, but code that runs after the try block entirely is unaffected by exceptions from within it (they'd have already been handled or would have propagated further up).
Example
try: print("Step 1") value = int("not a number") # raises ValueError here print("Step 2") # never reached except ValueError: print("Caught a ValueError") print("Continues normally after the try/except block")
💡 Emphasize that execution jumps immediately to the matching except the instant an exception is raised — code after the failing line, even within the same try block, is skipped entirely, not just the specific failing statement.
What is the role of except in exception handling?
Answer
except catches and handles a specific exception type (or tuple of types) raised inside the preceding try block, letting the program recover instead of crashing.
You can have multiple except clauses for different exception types, and Python checks them in order, executing only the first one that matches. Catching a broad type like Exception before a more specific one like ValueError means the specific clause will never actually run — order matters.
Example
def safe_divide(a, b): try: return a / b except ZeroDivisionError: return "Cannot divide by zero" except TypeError: return "Both arguments must be numbers" print(safe_divide(10, 0)) # 'Cannot divide by zero' print(safe_divide(10, "2")) # 'Both arguments must be numbers' print(safe_divide(10, 2)) # 5.0
What is the purpose of the else clause in a try/except statement?
Answer
The else block runs only if the try block completed without raising any exception. It's used to separate "code that might fail" (in try) from "code that should only run on success" (in else), keeping the try block minimal and making error sources easier to pinpoint.
A common mistake is putting success-dependent code directly inside the try block after the risky operation — this makes it unclear (and can accidentally suppress errors from) code that wasn't actually the risky part. else fixes this by only running after the try block is confirmed to have succeeded cleanly.
Example
try: number = int("42") # the risky operation except ValueError: print("Invalid number") else: print(f"Parsed successfully: {number}") # only runs if no exception occurred doubled = number * 2 # safely assumes 'number' is valid here print(doubled)
💡 Frame else as a readability and correctness tool — "it keeps the try block limited to only the line that can actually fail, so I don't accidentally catch an unrelated exception raised by my success-path code."
What is the purpose of the finally clause?
Answer
The finally block always executes — whether or not an exception occurred, and even if the exception was never caught, or if a return statement ran inside the try / except. It's used for guaranteed cleanup (closing files, releasing locks, disconnecting from a database).
finally is the closest Python gets to a language-level guarantee for cleanup logic. Its only real exception is if the entire process is killed abruptly (e.g., os._exit() or a hard crash) — under normal exception flow, including uncaught exceptions and return / break / continue inside the try, finally still runs.
Example
def read_config(path): f = None try: f = open(path) return f.read() except FileNotFoundError: return "default config" finally: if f: f.close() # guaranteed to run either way print("File closed") print(read_config("missing.txt"))
💡 Mention that a with statement (context manager) is usually cleaner than manual try / finally for resource cleanup specifically — but finally is still essential for cleanup logic that isn't resourceacquisition-shaped.
What is the correct order of try, except, else, and finally?
Answer
The required order is try → except (one or more) → else (optional) → finally (optional). Only try is mandatory; the rest are optional but must appear in this relative order if present.
A try block needs at least one except or a finally to be valid — try alone with nothing following it is a SyntaxError.
Example
try: print("1. try: attempt the risky operation") # no exception here except ValueError: print("2. except: only runs if a ValueError was raised") else: print("3. else: only runs if NO exception was raised") finally: print("4. finally: always runs, no matter what") # Output: # 1. try: attempt the risky operation # 3. else: only runs if NO exception was raised # 4. finally: always runs, no matter what
💡 Being able to state and demonstrate this order fluently, including which parts are optional, is a quick fluency check interviewers use to gauge hands-on experience versus surface familiarity.
How do you raise exceptions manually in Python?
Answer
Use the raise statement with an exception instance (or class): raise ValueError("message"). This immediately stops normal execution and begins propagating the exception up the call stack, exactly like a built-in error would.
You should prefer built-in exception types (ValueError, TypeError, KeyError, etc.) when they accurately describe the problem, since callers and libraries know how to handle them generically — reach for a custom exception class (Q123) mainly when no built-in type captures the specific situation.
Example
def set_age(age): if age < 0: raise ValueError("Age cannot be negative") return age set_age(-5) # raises: ValueError: Age cannot be negative
💡 Prefer raise ValueError("clear message") over generic raise Exception(".") — a specific, well-known exception type lets calling code catch it precisely rather than being forced into an overly broad except Exception:.
How do you create custom exceptions in Python?
Answer
Define a new class that inherits from Exception (or a more specific built-in exception), optionally adding extra attributes or overriding __init__ to carry additional context about the failure.
Custom exceptions are especially valuable in libraries and larger applications: they let calling code catch your specific error types precisely, and can carry structured data (like an error code or the invalid value) rather than forcing everything into a string message.
Example
class InsufficientFundsError(Exception): """Raised when an account doesn't have enough balance for a withdrawal.""" def __init__(self, balance, amount): self.balance = balance self.amount = amount super().__init__(f"Cannot withdraw {amount}, balance is only {balance}") def withdraw(balance, amount): if amount > balance: raise InsufficientFundsError(balance, amount) return balance - amount try: withdraw(100, 150) except InsufficientFundsError as e: print(e) # Cannot withdraw 150, balance is only 100 print(e.amount, e.balance) # 150 100 -- structured data, not just a string
💡 Highlight that a custom exception can carry structured data (like e.amount, e.balance above), not just a message — this is a meaningful advantage over generic exceptions that many candidates overlook.
How do you catch multiple exceptions in Python?
Answer
You can either write multiple except clauses (one per type, allowing different handling logic for each), or catch several types in one clause using a tuple: except (TypeError, ValueError):.
Use separate except clauses when different exception types need genuinely different handling logic; use a single tuple-based clause when the handling logic is identical regardless of which of those specific exceptions occurred.
Example
def parse_and_divide(a, b): try: return int(a) / int(b) except (ValueError, TypeError) as e: # same handling for both print(f"Invalid input: {e}") except ZeroDivisionError: # different handling print("Cannot divide by zero") parse_and_divide("10", "0") # Cannot divide by zero parse_and_divide("abc", "2") # Invalid input: invalid literal for int() with base 10: 'abc'
💡 Mention Python 3.11's except* (exception groups) if the conversation goes deep on modern Python — it's designed specifically for handling multiple simultaneous exceptions from concurrent code, a newer and less commonly known feature.
What is exception chaining, and what does raise. from. do?
Answer
Exception chaining preserves the original exception's context when you raise a new one in its except block. raise NewError(.) from original_error explicitly links the two, so tracebacks show both the root cause and the new exception, rather than losing the original error's information.
Even without from, Python automatically chains exceptions raised inside an except block (shown in the traceback as "During handling of the above exception, another exception occurred"). Using raise. from. explicitly documents the causal relationship, while raise. from None deliberately suppresses the chain when the original exception isn't relevant context for the caller.
Example
class ConfigError(Exception): pass def load_config(): try: with open("config.json") as f: return f.read() except FileNotFoundError as e: raise ConfigError("Could not load configuration") from e # traceback shows both: the original FileNotFoundError AND ConfigError, # with a clear "caused by" relationship between them try: load_config() except ConfigError as e: print(e) # Could not load configuration print(e.__cause__) # the original FileNotFoundError instance
💡 Mentioning __cause__ (explicit, via from) versus __context__ (implicit, automatic chaining without from) as the two different attributes involved shows you've actually read tracebacks carefully, not just used try/except mechanically.
What is the exception hierarchy in Python?
Answer
All exceptions inherit from BaseException. Its main branches are SystemExit, KeyboardInterrupt, GeneratorExit, and Exception — and Exception is the parent of nearly everything you'd normally catch, including ArithmeticError, LookupError, ValueError, TypeError, and OSError.
Understanding the hierarchy matters because catching a parent exception type also catches all of its subclasses — except LookupError: catches both KeyError and IndexError, since both inherit from LookupError.
Example
print(IndexError.__mro__) # (<class 'IndexError'>, <class 'LookupError'>, <class 'Exception'>, <class 'BaseException'>, <class 'object'>) try: [1, 2, 3][10] except LookupError: # catches IndexError because of the hierarchy print("Some kind of lookup failed") try: {"a": 1}["missing"] except LookupError: # also catches KeyError, same base class print("Some kind of lookup failed")
💡 Knowing that IndexError and KeyError share a common parent (LookupError) — and being able to explain when you'd deliberately catch at that shared level instead of each type individually — is a good depth signal here.
What are best practices for exception handling in Python?
Answer
Catch the most specific exception type possible, never use a bare except: (which also catches KeyboardInterrupt and SystemExit), avoid silently swallowing exceptions without at least logging them, and keep try blocks as small as possible around only the risky line(s).
A "bare except" (except: with no type at all) is one of the most criticized anti-patterns in Python — it catches literally everything, including exceptions meant to terminate the program, and can mask bugs that should have crashed loudly during development.
Example
# Anti-pattern: bare except, silently swallowed, huge try block def bad_version(): try: data = fetch_data() result = process(data) save(result) except: # catches EVERYTHING, including Ctrl+C! pass # silently hides all failures # Better: specific exception, minimal scope, logged failure import logging def good_version(): try: data = fetch_data() except ConnectionError: logging.exception("Failed to fetch data") return None result = process(data) # outside try -- not expected to fail the same way save(result) return result
What is the difference between except Exception and a bare except:?
Answer
except Exception: catches all "normal" errors but deliberately excludes SystemExit, KeyboardInterrupt, and GeneratorExit (since they don't inherit from Exception). A bare except: catches absolutely everything, including those — which is almost never what you actually want.
This distinction is exactly why the exception hierarchy (Q126) separates Exception from the other direct children of BaseException — it gives you a sensible "catch nearly everything reasonable" option (except Exception:) without accidentally intercepting process-control signals.
Example
import sys def risky(): try: sys.exit(1) # raises SystemExit except Exception: print("This won't print -- SystemExit isn't an Exception subclass") def too_broad(): try: sys.exit(1) except: # bare except -- catches SystemExit too! print("This WILL print -- and the program won't actually exit as intended")
💡 If asked "what's wrong with except: " directly, this SystemExit/KeyboardInterrupt scenario is the concrete, memorable example to give rather than a vague "it's too broad."
What is the difference between handling an exception and validating input beforehand?
Answer
This is Python's EAFP ("Easier to Ask Forgiveness than Permission") versus LBYL ("Look Before You Leap") design philosophies. EAFP tries the operation and handles failure via try / except; LBYL checks preconditions with if statements before attempting the operation at all. Python idiomatically favors EAFP.
EAFP is generally preferred in Python for two reasons: it avoids race conditions where a condition could change between the check and the actual operation (a "time-of-check to time-of-use" bug), and it's often faster in the common case, since no upfront check is needed when the operation usually succeeds.
Example
d = {"a": 1} # LBYL -- "look before you leap" if "b" in d: value = d["b"] else: value = 0 # EAFP -- "easier to ask forgiveness than permission" (more Pythonic) try: value = d["b"] except KeyError: value = 0 # LBYL has a real race-condition risk with shared/external resources: import os if os.path.exists("file.txt"): # file could be deleted right here by another process! with open("file.txt") as f: # ...causing this to fail anyway data = f.read()
💡 The file-existence race condition example is the most convincing illustration of why EAFP is preferred, not just a style preference — LBYL's check-then-use pattern is inherently unsafe against concurrent changes from other processes or threads.
How would you log exceptions properly in a production application?
Answer
Use the standard logging module's.exception() method (or logging.error(., exc_info=True)) inside an except block — it automatically captures and records the full traceback, not just the exception's string message, which is essential for diagnosing issues after the fact.
Using print() for error reporting in production code is a common but serious anti-pattern: it doesn't capture the traceback, isn't searchable/filterable the way structured logs are, and typically doesn't get written anywhere durable in a deployed service. logging.exception() should be called specifically from within an except block, since it relies on the currently-handled exception's context.
Example
import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def process_order(order_id): try: risky_operation(order_id) except Exception: logger.exception(f"Failed to process order {order_id}") # logs the message AND the full traceback automatically raise # re-raise if the caller also needs to know about the failure def risky_operation(order_id): raise ValueError("Invalid order data")
💡 Mentioning logger.exception() specifically (versus plain logger.error()) is a strong, concrete signal of production experience — it's a small API detail that most tutorial-only learners never encounter.
Recommended resourcesAffiliate links · may earn us a commission