How Does Exception Handling Work in Python?
Learn how Python exception handling works with try, except, else and finally blocks, raising errors, and custom exceptions, explained with clear code examples.
Expected Interview Answer
Exception handling in Python uses try, except, else, and finally blocks to catch and respond to runtime errors so a program can recover gracefully instead of crashing.
Code that might fail goes in the try block; if an exception is raised, Python jumps to the matching except block based on the exception type. The optional else block runs only when no exception occurred, and finally always runs for cleanup such as closing files. You can raise exceptions yourself with raise and define custom exception classes by subclassing Exception.
- Prevents abrupt program crashes
- Separates error-handling logic from normal flow
- Allows targeted responses per exception type
- Guarantees cleanup with finally
- Supports custom, meaningful error types
AI Mentor Explanation
A wicketkeeper standing back is exception handling in motion: the try is the delivery, an edge is the unexpected error, and the keeper's gloves are the except block catching it before it races to the boundary. The finally is the fielders resetting for the next ball no matter what happened, so play never simply collapses.
Step-by-Step Explanation
Step 1
Wrap risky code in try
Place statements that might raise an error inside the try block.
Step 2
Catch with except
Add one or more except clauses to handle specific exception types like ValueError or KeyError.
Step 3
Use else for success
The optional else block runs only if the try block completed without raising an exception.
Step 4
Clean up with finally
The finally block always executes, making it ideal for releasing resources like files or connections.
Step 5
Raise when needed
Use raise to signal errors yourself, optionally with a custom Exception subclass for clarity.
What Interviewer Expects
- Correct roles of try, except, else and finally
- Catching specific exception types rather than bare except
- Knowing finally runs even after return or an unhandled error
- Ability to raise and define custom exceptions
- Awareness of exception chaining and the as keyword
Common Mistakes
- Using a bare except that silently swallows all errors
- Catching Exception too broadly and hiding bugs
- Putting cleanup in except instead of finally
- Confusing else (runs on success) with finally (always runs)
- Raising strings instead of exception instances
Best Answer (HR Friendly)
“Exception handling is Python's way of dealing with errors without crashing. You put risky code in a try block, describe what to do if it fails in an except block, and use finally for cleanup that should always happen, like closing a file.”
Code Example
def read_ratio(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
return None
except TypeError as err:
print(f"Bad types: {err}")
return None
else:
# runs only if no exception was raised
print("Division succeeded")
return result
finally:
# always runs, for cleanup
print("Done attempting division")
print(read_ratio(10, 2)) # 5.0
print(read_ratio(10, 0)) # None
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough balance")
return balance - amountFollow-up Questions
- What is the difference between the else and finally blocks?
- Why is a bare except considered bad practice?
- How do you create and raise a custom exception?
- What does exception chaining with 'raise ... from' do?
- How can you catch multiple exception types in one except clause?
MCQ Practice
1. Which block always executes, whether or not an exception is raised?
The finally block runs unconditionally, making it ideal for cleanup like closing files or connections.
2. When does the else block of a try statement run?
The else block executes only if the try block completes without raising any exception.
3. How do you signal an error yourself in Python?
Python uses the raise keyword with an exception instance, e.g. raise ValueError('bad input').
Flash Cards
What are the four exception-handling blocks? — try, except, else, and finally.
When does finally run? — Always — after try/except, even if an exception propagates or a return occurs.
When does else run? — Only when the try block finishes with no exception raised.
How do you make a custom exception? — Subclass Exception, e.g. class MyError(Exception): pass, then raise it.