Chapter 12

Exceptions

The else clause on try runs when no exception occurs. finally ALWAYS runs — even after return. raise e loses the original traceback.

Questions: 15
Difficulty: ★★★☆☆
try/except/else/finally order: try runs first. If exception → except. If no exception → else. finally ALWAYS runs, regardless of what happened. This is the complete execution order.
Basic try/except
Q 01Predict the Output
try:
    x = 1 / 0
except ZeroDivisionError:
    print("caught")
else:
    print("no error")
finally:
    print("always")
Output
caught always
Why? 1/0 raises ZeroDivisionError → caught by except. Since an exception occurred, the else block is skipped. finally always runs. The else clause only runs when the try block completes with NO exception.
Q 02Predict the Output
try:
    x = 1 / 1   # no error
except ZeroDivisionError:
    print("caught")
else:
    print("no error")
finally:
    print("always")
Output
no error always
Why? No exception was raised → except is skipped → else runs. Then finally always runs. The else clause is useful for code that should only run if the try succeeded — separating it from try makes the intent clearer.
finally Always Runs
Q 03Predict the Output
def f():
    try:
        return 1
    finally:
        print("finally ran")

result = f()
print(result)
Output
finally ran 1
Why? finally runs even when the try block contains a return. Python notes the return value, runs finally, then actually returns. The return value is still 1. Use finally for cleanup (closing files, releasing locks) that must happen regardless.
Q 04Multiple Choice
def f():
    try:
        return 1
    finally:
        return 2   # return in finally!

print(f())
Answer: b) 2.

A return in finally overrides the return in try. The finally return of 2 replaces the pending return of 1. This also suppresses any exception from the try block. Putting return in finally is generally considered bad practice for this reason.
Exception Hierarchy
Q 05Multiple Choice
try:
    raise ValueError("bad value")
except Exception as e:
    print(f"caught: {type(e).__name__}")
Answer: a) "caught: ValueError".

except Exception catches any exception that is a subclass of Exception. ValueError is a subclass of Exception. The except clause catches the actual ValueError instance — type(e).__name__ shows the actual type, not "Exception".
Q 06Predict the Output
try:
    raise ValueError
except ValueError:
    print("ValueError")
except Exception:
    print("Exception")
except:
    print("bare except")
Output
ValueError
Why? Python checks except clauses top to bottom and runs the FIRST match. ValueError matches first → "ValueError" is printed. The other clauses are skipped. Order matters: always put more specific exceptions before broader ones.
raise vs raise e
Q 07Multiple Choice
try:
    try:
        1 / 0
    except ZeroDivisionError as e:
        raise e   # vs just: raise
except ZeroDivisionError:
    print("caught again")
Answer: b).

Both raise and raise e re-raise the exception. However, raise e creates a new traceback starting from this line, losing the original context. Bare raise re-raises with the original traceback intact. Always use bare raise to re-raise — never raise e.
Q 08Predict the Output
try:
    raise ValueError("original")
except ValueError:
    raise RuntimeError("wrapped") from None
Output
RuntimeError: wrapped
Why? raise NewError from None raises a new exception and explicitly suppresses the exception chain (no "During handling of above exception..." message). Without from None, Python shows both the original and new exception. from original_exc chains them explicitly. This is used when you want clean error messages at API boundaries.
Custom Exceptions
Q 09Predict the Output
class MyError(ValueError):
    pass

try:
    raise MyError("custom")
except ValueError:
    print("caught by ValueError")
except MyError:
    print("caught by MyError")
Output
caught by ValueError
Why? MyError inherits from ValueError. The first matching except wins. ValueError comes first and matches MyError (since MyError IS-A ValueError). The except MyError clause is never reached. To catch MyError specifically, put it BEFORE ValueError.
Q 10Multiple Choice
try:
    pass
except:
    print("caught")
else:
    print("no error")
Answer: b) "no error".

pass raises no exception. So the except is skipped and the else runs. Remember: bare except: catches everything including KeyboardInterrupt and SystemExit — always avoid it. Use except Exception: at minimum.
Exception Info
Q 11Predict the Output
try:
    raise ValueError("bad", 42)
except ValueError as e:
    print(e.args)
    print(str(e))
Output
('bad', 42) ('bad', 42)
Why? Exceptions store arguments in .args (a tuple). You can pass multiple args to an exception: ValueError("bad", 42). str(e) on a multi-arg exception returns the tuple representation. For single-arg exceptions: str(ValueError("bad")) returns just "bad".
Q 12Predict the Output
try:
    x = int("abc")
except (ValueError, TypeError) as e:
    print(f"Error: {type(e).__name__}")
Output
Error: ValueError
Why? You can catch multiple exception types in one except clause by passing a tuple: except (ValueError, TypeError). int("abc") raises ValueError (can't convert non-numeric string). This is cleaner than writing two separate except clauses for the same handling code.
Context Managers
Q 13Multiple Choice
try:
    with open("nonexistent.txt") as f:
        data = f.read()
except FileNotFoundError:
    print("file missing")
Answer: a) "file missing".

with statements can be inside try/except. The FileNotFoundError raised by open() propagates out of the with and is caught by the except. The with statement ensures cleanup even if an exception occurs inside its block.
Q 14Predict the Output
def f():
    try:
        return "try"
    except:
        return "except"
    else:
        return "else"
    finally:
        return "finally"

print(f())
Output
finally
Why? When finally has a return, it overrides ALL other returns. The try would return "try", then finally runs and returns "finally" — overriding everything. The else is also skipped because the try already returned. This is why putting returns in finally is dangerous.
Q 15Multiple Choice
import sys

try:
    sys.exit(0)
except Exception:
    print("caught")
Answer: b) Program exits.

sys.exit() raises SystemExit. SystemExit is NOT a subclass of Exception — it inherits directly from BaseException. except Exception only catches Exception subclasses. To catch SystemExit, use except BaseException or except SystemExit. Same applies to KeyboardInterrupt.
← Chapter 11: Iterators & Generators Chapter 13: Python Gotchas →