Interview Q&A · Python · 15 questions in this topic

Exception Handling — Python Interview Q&A

All Python topics

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

Example.pypython
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

Example.pypython
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

Example.pypython
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

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits