Python Exception Handling Interview Questions
Last updated 2026-11-19
Exception handling questions check whether you write code that fails predictably. Interviewers look for correct use of try, except, else and finally, specific exception types, custom exception classes, and an understanding of what happens to the return value when finally also returns.
The questions below include the output puzzles that catch most candidates, such as return inside finally and exception variable scoping, along with the design questions about when to raise, catch and re-raise.
| Level | Fresher to 3 years |
|---|---|
| Focus | try/except flow, custom exceptions, cleanup |
| Version | Python 3.10 and later |
Rules worth stating in an interview
Catch the narrowest exception you can handle, keep the try block small, never use a bare except, and do not swallow errors silently. Use finally or a context manager for cleanup.
- Exceptions derive from BaseException; ordinary ones derive from Exception
- KeyboardInterrupt and SystemExit sit outside Exception on purpose
- Use raise without arguments to re-raise and keep the traceback
Next steps
File-related failures are discussed with examples in Python file handling. The core semantics of names and scope are on the main Python page, and the full plan is in how to crack a Python interview.
Python Exception Handling Interview Questions: questions with worked answers
1 What is the difference between syntax errors and exceptions?
easyA syntax error is detected when the source is parsed, before any code runs, so the program never starts. An exception is raised at runtime when a valid statement fails, such as dividing by zero or indexing past the end. Exceptions can be caught with try and except, while a syntax error in the same file cannot, though code compiled at runtime with eval or exec can raise SyntaxError that you catch.
2 Explain try, except, else and finally.
easytry holds the risky code. except handles a matching exception. else runs only if the try block finished without raising, and keeps unrelated code out of the try. finally always runs, whether or not an exception occurred, and even on return, break or continue, so it is used for cleanup.
pythondef f(x): try: r = 10 / x except ZeroDivisionError: print("zero") else: print("ok", r) finally: print("done") f(2) # ok 5.0 / done f(0) # zero / done3 Predict the output: return inside try and finally.
hardfinally runs before the function actually returns. If finally itself contains a return, it overrides the earlier return and also swallows any exception in flight. That is why returning from finally is considered bad practice. If finally only runs a statement, the value computed in try is kept.
pythondef a(): try: return "try" finally: print("cleanup") def b(): try: return "try" finally: return "finally" print(a()) # cleanup, then try print(b()) # finally4 What is the order for multiple except clauses?
mediumPython checks except clauses from top to bottom and runs the first that matches, including subclasses. So a broad clause such as Exception placed first would shadow the specific ones below it. List the most specific types first. You can group several types in a tuple, as in except (KeyError, IndexError). Since Python 3.11 you can also use except* for exception groups.
pythontry: [][1] except KeyError: print("key") except (IndexError, TypeError) as e: print("index or type:", e) # index or type: list index out of range5 Why is a bare except a bad idea?
mediumA bare except catches everything, including KeyboardInterrupt and SystemExit, so the user cannot stop the program with Ctrl+C and real bugs such as typos are hidden. If you really need a catch-all at a boundary, catch Exception, log the traceback and re-raise or exit deliberately. Silent pass blocks make failures nearly impossible to debug.
6 How do you create a custom exception?
mediumSubclass Exception, or a more specific built-in such as ValueError. Keep a base exception for your package so callers can catch all your errors, and add attributes when handlers need data. Name them with an Error suffix.
pythonclass AppError(Exception): pass class InsufficientFunds(AppError): def __init__(self, need, have): super().__init__(f"need {need}, have {have}") self.need, self.have = need, have try: raise InsufficientFunds(100, 40) except AppError as e: print(e, e.need) # need 100, have 40 1007 What is the difference between raise, raise e and raise ... from?
mediumA bare raise inside an except block re-raises the active exception with its original traceback. raise e re-raises the same object but adds the current line to the traceback. raise NewError from e sets __cause__ to show an explicit chain, used when translating a low-level error into a domain error. raise NewError from None suppresses the chained context.
pythontry: try: int("x") except ValueError as e: raise RuntimeError("bad config") from e except RuntimeError as err: print(type(err.__cause__).__name__) # ValueError8 Predict the output: the exception variable is deleted after the except block.
hardIn Python 3, the name bound by as e is deleted at the end of the except clause to avoid reference cycles with the traceback. Using e afterwards raises NameError. Copy it into another name inside the block if you need it later.
pythontry: 1 / 0 except ZeroDivisionError as e: saved = e print(saved) # division by zero print(e) # NameError: name 'e' is not defined9 What is a context manager and how does it help with exceptions?
mediumA context manager defines enter and exit logic for a with block. __exit__ is called even when the block raises, receiving the exception details, so resources such as files and locks are released correctly, and returning True from __exit__ suppresses the exception. Use contextlib.contextmanager to write one with a generator and try/finally.
pythonfrom contextlib import contextmanager @contextmanager def opened(name): print("open", name) try: yield name finally: print("close", name) with opened("f"): pass # open f / close f10 What is the difference between assert and raise?
easyassert condition, message is a debugging aid that raises AssertionError when the condition is false, and it is removed completely when Python runs with the -O flag. Never use it to validate user input or enforce security. Use raise with a proper exception type for conditions that must hold in production.
11 What is the EAFP versus LBYL style?
mediumEAFP, easier to ask forgiveness than permission, tries the operation and handles failure, which is idiomatic Python and avoids races between check and use. LBYL, look before you leap, checks conditions first. Use EAFP for dictionary access and file opening, where the state may change between check and use, and LBYL when a failure is expensive or side-effectful.
pythond = {"a": 1} try: v = d["b"] except KeyError: v = 0 print(v) # 0 print(d.get("b", 0)) # 0 (even simpler)12 What are exception groups and except* in Python 3.11?
hardExceptionGroup bundles several unrelated exceptions raised together, for example from concurrent tasks. The except* syntax matches by type against the members, and each clause handles the matching subset while the rest propagate. It is used by asyncio.TaskGroup, which reports every failing task rather than only the first.
pythontry: raise ExceptionGroup("batch", [ValueError(1), TypeError(2)]) except* ValueError as eg: print("value", eg.exceptions) # value (ValueError(1),) except* TypeError as eg: print("type", eg.exceptions) # type (TypeError(2),)13 What is the exception hierarchy at a glance?
mediumBaseException is the root. Below it sit SystemExit, KeyboardInterrupt, GeneratorExit and Exception. Almost everything you handle, such as ValueError, TypeError, KeyError, IndexError, OSError and ZeroDivisionError, derives from Exception. LookupError is the parent of KeyError and IndexError, and ArithmeticError is the parent of ZeroDivisionError. Catching a parent catches its children.
Frequently asked questions
Does finally always run?
Almost always. It runs after return, break, continue and exceptions. It does not run if the process is killed or the interpreter crashes, or if os._exit is called.
Can I have try without except?
Yes, with finally, as in try and finally for cleanup, or with only except, but try alone is a syntax error.
What does else do on a loop?
On for and while loops, else runs when the loop finishes without hitting break. It is different from the else on try, though both mean no early exit happened.
How should I log exceptions?
Use logging.exception inside an except block, which records the message with the full traceback, then handle or re-raise. Do not print and continue silently.
Related guides
More in Programming Language Interview Questions by Language
- Python File Handling Interview Questions
- Python Generators and Iterators Interview Questions
- Python Interview Questions and Answers
- Python Lambda, Map, Filter and Reduce Interview Questions
- Python List, Dict and Set Interview Questions
- Python Memory Management Interview Questions
- Python Multithreading and Multiprocessing Interview Questions
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions
- SQL Indexes Interview Questions