Exceptions and Files: Interview Questions
50 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Interviewers use exceptions and files to see whether you write code that fails safely. Short, exact answers on finally, bare except and with show that habit quickly.
Recap: try, except, else and finally
An exception is an object that Python raises when something goes wrong. If no except block handles it, the program stops and prints a traceback.
Each block has one job. try holds the risky line, except handles a named error, else runs only if nothing failed, and finally always runs.
def read_qty(text): try: qty = int(text) except ValueError: print("bad number") return 0 else: print("ok") return qty finally: print("done")
print(read_qty("4"))print(read_qty("x"))Example 1 · else and finally in order
def divide(a, b): try: result = a / b except ZeroDivisionError: print("cannot divide by zero") return None else: print("division worked") return result finally: print("finished")
print(divide(10, 4))print(divide(1, 0))division worked finished 2.5 cannot divide by zero finished None
What this code does
elseruns only whentryraised nothing.finallyruns in both calls, just before eachreturnhands back its value.- Each
printof the result comes after that call'sfinishedline.
Each call prints done last, even though both return early. Catch the specific error you expect, not every error.
Recap: raise, custom errors and the hierarchy
The exception hierarchy is the tree of exception classes. BaseException is the root, Exception is the parent of normal errors, and an except block also catches all subclasses.
raise throws an exception. A custom error is a small class that extends Exception. Use raise ... from err to keep the original cause.
class InsufficientFunds(Exception): pass
def withdraw(balance, amount): if amount > balance: raise InsufficientFunds(f"need {amount - balance} more") return balance - amount
try: withdraw(100, 150)except InsufficientFunds as err: print(err)Example 2 · Specific errors and chaining
def parse_mark(text): try: return int(text) except ValueError as err: raise ValueError(f"invalid mark: {text!r}") from err
try: parse_mark("ab")except ValueError as err: print(err) print(type(err.__cause__).__name__) print(issubclass(FileNotFoundError, OSError))invalid mark: 'ab' ValueError True
What this code does
raise ... from errstores the original error as__cause__, so the full story survives in a traceback.FileNotFoundErroris a subclass ofOSError, soexcept OSErroralso catches it.
except Exception catches this error, but never KeyboardInterrupt or SystemExit, because those extend BaseException directly. A bare except: catches them too, which is why it is a bad habit.
Recap: files and the with statement
A context manager is an object used with with. It sets something up on entry and always cleans up on exit, even if an exception is raised inside the block.
open() gives a file object that must be closed. with open(...) closes it for you. Name the encoding so the text reads the same on every computer.
import tempfile, os
folder = tempfile.mkdtemp()path = os.path.join(folder, "orders.txt")with open(path, "w", encoding="utf-8") as f: f.write("A100\nA101\n")with open(path, encoding="utf-8") as f: for line in f: print(line.strip())print(f.closed)Example 3 · Write, append and read a file safely
import tempfilefrom pathlib import Path
with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "marks.txt" path.write_text("Asha 80\nRavi 72\n", encoding="utf-8") with open(path, "a", encoding="utf-8") as f: f.write("Meena 91\n") with open(path, encoding="utf-8") as f: total = sum(int(line.split()[1]) for line in f) print(total) try: open(Path(folder) / "missing.txt") except FileNotFoundError: print("no such file")243 no such file
What this code does
- Mode
"a"adds to the end, while"w"would erase the old content first. - Opening a missing file raises
FileNotFoundError; catch that exact error to handle it. The temporary folder is removed when the outerwithends.
Looping over the file reads one line at a time, so even a huge file fits in memory. f.closed is True after the block, because with closed it.
Next step
Check your understanding
12 quick questions