Python
Exception Handling
36 flashcards · answers and spaced-repetition review in the KnowCard app
What does this print? (nested try)
```
try:
try:
raise TypeError
except IndexError:
print("inner")
except TypeError:
print("outer")
```
What happens if an exception is raised inside an except (or else / finally) branch — can a later except of the same try catch it?
In a try/except/else block, when does the else branch run?
What does this print?
```
def f():
try:
return 1
finally:
print("cleanup")
print(f())
```
What does this function return?
```
def f():
try:
return "try"
finally:
return "finally"
```
Why is ordering except branches general-before-specific a bug?
```
try:
risky()
except Exception:
a()
except ValueError:
b()
```
What is the anti-pattern with a bare except: (no exception type), and what's the safer alternative?
Why doesn't except Exception catch KeyboardInterrupt or SystemExit?
What does this print?
```
try:
raise KeyError("k")
except (ValueError, KeyError) as e:
print("got", e.args[0])
```
What's the difference between bare raise and raise TypeError when re-raising inside an except branch?
Inside an except IndexError: block you write raise RuntimeError("boom"). What does the traceback show besides the RuntimeError?
What's the difference between raise X from Y and raise X from None?
What base class should a custom exception inherit from, and what's the consequence of getting it wrong?
What does this print?
```
class E(Exception):
def __init__(self, bal, amt):
super().__init__(bal, amt)
self.amt = amt
try:
raise E(100, 250)
except E as e:
print(e.args, e.amt)
```
A custom exception with extra attributes prints MyError: with no useful message in the traceback. Why, and how do you fix it?
What is EAFP, and why is it the Pythonic choice over LBYL here?
```
# LBYL
if key in d:
use(d[key])
```
What does this print?
```
try:
print("a")
raise ValueError
except ValueError:
print("b")
else:
print("c")
finally:
print("d")
```
What does raise "oops" do in Python 3?
When catching two or more exception types in a single except branch, what's the correct syntax?
What does e.args hold for e = ValueError("bad", 42)?
What's the relationship between ImportError and ModuleNotFoundError, and when is each raised?
Why does this raise UnboundLocalError instead of printing 10?
x = 10
def f():
print(x)
x = 20
f()
You want to catch file-system problems — missing file, no permission, connection timeout — without listing each one. What single class covers them, and name a few of its subclasses.
Can you wrap code in try/except SyntaxError to recover from a syntax error? When does that actually work?
What exception signals that an iterator is exhausted, and who normally raises and catches it?
Which Python 3.11 feature lets several unrelated exceptions be raised together and handled selectively, and what new syntax goes with it?
When a subfunction raises an exception, its own execution ends immediately. What are the three things each parent function up the call chain can then do?
In Python 3, what's the difference between raise ValueError (the bare class) and raise ValueError("bad value")?
What exactly is a 'traceback', and what does simply seeing one tell you about your program?
What does this print?
lst = [7, 1, 3, 5, -12]
assert min(lst) == -12
assert sum(lst) == 0, "sum is broken"
Why is it dangerous to rely on assert for validating untrusted input or enforcing a security check in production?
How does a warning (like DeprecationWarning) differ from a normal exception, and how can you make warnings behave like exceptions?
Which built-in exception does each expression raise, and what's the rule that decides?
int("hello") # (a)
int([1, 2]) # (b)
You want a single except clause that catches both a bad list index and a missing dict key. Which base class do you catch?
What common base class do ZeroDivisionError and OverflowError share, and what is each one for?
What is RuntimeError used for, and why do abstract base-class methods often raise NotImplementedError?
Start learning today
Free to start — download the app or use it in your browser.
