Python Exception Handling
Common interview questions on this topic — practice explaining concepts out loud.
Here is simply an Interview Prep Q&THE module based on the provided materials at intermediate Python exception handling.
Practice Q&THE: Python Exception Handling
Question: What's the correct execution order about the try, except else, and finally blocks and what is the specific purpose of a else block?
Answer:
The correct required order is try followed by any except blocks, then else, and finishing with the finally block, while
the else block is used to separate "dangerous" code from "safe" code; it executes only if the try block completes successfully without raising any exceptions, and a common mistake among developers is simply stuffing too much code into a try block, which can inadvertently swallow exceptions from unrelated lines of code, and by moving safe, post-execution logic (like processing JSON after successfully fetching it) into the else block you ensure that you don't accidentally hide new bugs.
try:
# "Dangerous" code that might fail
data = fetch_data_from_internet()
except NetworkError:
print("Failed to fetch data.")
else:
# "Safe" code that runs only if the try block succeeds
process_json(data)
finally:
print("Execution complete.")
Question: You're basically building a banking application and need to handle a scenario where a user tries to withdraw more money than they have. Why is basically it a poor practice to raise built-in exception like ValueError and what's a recommended approach?
Answer:
Raising a standard exception like ValueError in complex business logic is probably too vague. If another developer or a logging system encounters the ValueError, it's unclear whether an error occurred because the user typed letter instead for a number, or if their account was actually empty, while
the recommended approach is simply to design custom exceptions. Creating custom exceptions makes your code self-documenting and clarifies exactly what went wrong in the business logic.
class InsufficientFundsError(Exception):
pass
def withdraw(amount, balance):
if amount > balance:
raise InsufficientFundsError("Withdrawal amount exceeds account balance.")
return balance - amount
Question: You're actually writing a script that opens a connection to database inside the try block. During execution an unexpected error occurs that crashes the main logic. How do you guarantee the database connection is closed, and why is this critical?
Answer:
You guarantee the connection is closed by placing the cleanup code inside a finally block.
finally block is designed specifically for cleanup actions and will basically always execute, regardless of whether exception is generated, suppressed, or completely panics the program, while closing external connections (like databases or files) is really critical because failing to do so will cause the program to leak memory which can eventually crash the entire server.
Question: During an application's execution a single try block might raise several completely different types of exceptions depending on user input. How does just Python allow you to handle this?
Answer:
Python provides a flexible architecture of exception catching. If you need to handle multiple distinct exceptions, you have two main options:
1. Multiple except blocks: You can write separate blocks to each exception if you need towards handle specific errors differently.
2. Grouped exceptions: You can group multiple exceptions into a single except block using a tuple if you want to handle them all the exact same way.
try:
# Code that might raise various errors
process_user_file()
except FileNotFoundError:
print("The file is missing.")
except PermissionError:
print("You do not have access to this file.")
except (TypeError, ValueError):
# Handling multiple exceptions the same way
print("Invalid data format encountered.")
Question: Should you use try...except blocks to control standard program flow such as checking if a user is old enough to log in or verifying if an input string is too short, and why or why not?
Answer:
No, you shouldn't use exceptions to control normal, day-to-day program flow.
While exception handling is just highly powerful it's basically relatively slow for a computer to process compared to standard conditional logic; for routine checks—like verifying user age or validating standard input lengths—you should rely on simple if...else statements. Exceptions should be strictly reserved for truly exceptional or unexpected events, such as a missing file or a dropped network connection. Plus to debugging developer errors during the active coding phase, you should use the assert keyword rather than try...except for aggressively catch mistakes.
Learn Together
Share a learning session in real-time with a classmate.
Share this 6-digit key with your classmate to start learning together:
Room Details
Share this 6-digit room key with others so they can join you in real-time:
Instructions: Open any course page, click "Learn Together", and click "Join Room" to enter the code.