Unit 5: Exception handling - Practice Quiz
1 Which Python block contains code that might cause an exception?
except block
else block
try block
finally block
2 Which exception is raised when a number is divided by zero?
ValueError
TypeError
ZeroDivisionError
IndexError
3 Which block normally runs whether or not an exception occurs?
except block
try block
else block
finally block
4
When does the else block of a try statement run?
try block
finally block
5
In except ValueError as error:, what does error represent?
6
Which syntax catches both ValueError and TypeError in one handler?
except (ValueError, TypeError):
except [ValueError, TypeError]:
except ValueError and TypeError:
except ValueError or TypeError:
7 How can different exception types be given different handling code?
finally blocks
else blocks
except blocks
try keywords
8 When catching related exception classes, which handler should usually appear first?
9
If several except blocks could match an exception, which matching block runs?
10 Which statement correctly handles either a conversion error or an invalid operand type?
except ValueError, TypeError:
except (ValueError, TypeError):
except {ValueError, TypeError}:
except (ValueError + TypeError):
11 Which keyword is used to deliberately trigger an exception in Python?
except
raise
trigger
assertion
12
Which statement raises a built-in ValueError?
raise ValueError()
return ValueError()
except ValueError()
catch ValueError()
13
What does a bare raise statement do inside an except block?
14 Why might a function explicitly raise an exception?
15
Which statement raises an exception with the message Age cannot be negative?
except ValueError("Age cannot be negative")
raise ValueError("Age cannot be negative")
return ValueError("Age cannot be negative")
print ValueError("Age cannot be negative")
16 Which built-in class should a basic custom exception normally inherit from?
object
module
Exception
function
17
Which definition correctly creates a custom exception named InvalidAgeError?
class InvalidAgeError(exception): pass
def InvalidAgeError(Exception): pass
except InvalidAgeError(Exception): pass
class InvalidAgeError(Exception): pass
18
How is a custom exception named InvalidAgeError triggered?
except InvalidAgeError()
catch InvalidAgeError()
return InvalidAgeError()
raise InvalidAgeError()
19
Which handler catches a custom exception named InvalidAgeError?
except InvalidAgeError:
raise InvalidAgeError:
finally InvalidAgeError:
try InvalidAgeError:
20 What is a main benefit of defining a custom exception?
21
What is printed by the following code?
def parse_value(text):
try:
return int(text)
except ValueError:
return -1
print(parse_value("3.5"))
3
3.5
ValueError
-1
22
What is the output of this code?
try:
result = 10 // 2
except ZeroDivisionError:
print("error")
else:
print(result)
finally:
print("done")
done followed by 5
5 followed by error
error followed by done
5 followed by done
23
What is printed by the exception handler?
try:
int("python")
except ValueError as err:
print(type(err).__name__)
ValueError
TypeError
Exception
python
24
What is the output of the following function call?
def calculate():
try:
return 8 / 0
except ZeroDivisionError:
return 2
finally:
print("cleanup")
print(calculate())
ZeroDivisionError only
cleanup followed by 0
cleanup followed by 2
2 followed by cleanup
25
What happens when this code is executed?
try:
int("x")
except ValueError:
print("conversion failed")
10 / 0
conversion failed is printed
ZeroDivisionError is propagated
ValueError remains unhandled
26
Which handler correctly catches either ValueError or TypeError and stores the exception in err?
except ValueError, TypeError as err:
except ValueError or TypeError as err:
except [ValueError, TypeError] as err:
except (ValueError, TypeError) as err:
27
Assume missing.txt does not exist. Which handler runs?
try:
open("missing.txt")
except OSError:
print("OS")
except FileNotFoundError:
print("FILE")
FileNotFoundError handler
OSError handler
28
What does the following code print?
def convert(value):
try:
int(value)
except (TypeError, ValueError):
return "bad"
return "ok"
print(convert(None), convert("7"))
bad bad
bad ok
ok ok
ok bad
29
What is printed by this code?
try:
value = 4 / 0
except ArithmeticError:
print("arithmetic")
except ZeroDivisionError:
print("zero")
zero
arithmetic zero
arithmetic
30
What happens when this code runs?
try:
data = {}
print(data["name"])
except (ValueError, TypeError):
print("handled")
TypeError is propagated
None is printed
KeyError is propagated
handled is printed
31
Which statement should replace the comment to reject a negative quantity with an appropriate built-in exception?
def set_quantity(quantity):
if quantity < 0:
# replacement
return quantity
except ValueError("negative quantity")
return ValueError("negative quantity")
raise ValueError("negative quantity")
raise TypeError("negative quantity")
32
What occurs when load() is called?
def load():
try:
int("invalid")
except ValueError:
print("logged")
raise
load()
ValueError propagates without printing anything
RuntimeError replaces the original exception
logged is printed and execution continues
logged is printed and ValueError propagates
33
After the following handler raises RuntimeError, what is stored in the new exception's __cause__ attribute?
try:
int("x")
except ValueError as err:
raise RuntimeError("conversion failed") from err
ValueError object
conversion failed
RuntimeError object
None
34
Given the following class, what does raise Failure do?
class Failure(Exception):
pass
raise Failure
Failure class object
Exception class
Failure instance
35
What is the main effect of from None in this code?
try:
1 / 0
except ZeroDivisionError:
raise ValueError("invalid result") from None
ValueError from being raised
36
What is printed by this code?
class AgeError(Exception):
pass
def register(age):
if age < 0:
raise AgeError("invalid age")
try:
register(-2)
except Exception as err:
print(type(err).__name__)
ValueError
AgeError
Exception
invalid age
37
What does this code print?
class ScoreError(Exception):
def __init__(self, score):
self.score = score
super().__init__(f"score={score}")
try:
raise ScoreError(120)
except ScoreError as err:
print(err.score, str(err))
120 ScoreError
ScoreError score=120
120 score=120
score=120 120
38
Which handler catches the exception raised below?
class ValidationError(Exception):
pass
class EmailError(ValidationError):
pass
raise EmailError("invalid email")
except KeyError:
except ArithmeticError:
except ValidationError:
except TypeError:
39
What is the value of err.args in the handler?
class LimitError(Exception):
def __init__(self, limit):
self.limit = limit
super().__init__(f"limit={limit}")
try:
raise LimitError(5)
except LimitError as err:
print(err.args)
["limit=5"]
{"limit": 5}
("limit=5",)
(5,)
40
What is printed when withdraw(80, 50) is called?
class InsufficientFundsError(Exception):
def __init__(self, shortage):
self.shortage = shortage
super().__init__("insufficient funds")
def withdraw(amount, balance):
if amount > balance:
raise InsufficientFundsError(amount - balance)
return balance - amount
try:
print(withdraw(80, 50))
except InsufficientFundsError as err:
print(err.shortage)
30
-30
50
80
41
What is printed by the following code?
events = []
try:
try:
events.append('try')
except ValueError:
events.append('inner')
else:
events.append('else')
raise KeyError('missing')
finally:
events.append('finally')
except KeyError:
events.append('outer')
print(events)
['try', 'inner', 'finally', 'outer']
['try', 'else', 'outer', 'finally']
['try', 'else', 'finally']
['try', 'else', 'finally', 'outer']
42
What does f() return?
def f():
try:
raise ValueError('bad')
except ValueError:
return 'handled'
finally:
return 'final'
ValueError
None
'handled'
'final'
43
What happens when this code executes?
err = 'outer'
try:
raise ValueError('inner')
except ValueError as err:
saved = str(err)
print(err, saved)
UnboundLocalError
outer inner
inner inner
NameError
44
What is the result of this code?
class Manager:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return 'False'
with Manager():
raise RuntimeError('failure')
print('done')
RuntimeError
TypeError
False
done
45
What occurs when this code runs?
try:
raise KeyboardInterrupt()
except Exception:
print('caught')
finally:
print('cleanup')
caught and cleanup are printed
cleanup is printed, then the exception propagates
caught is printed, then execution continues
46
What is printed by the following code?
try:
raise TypeError('wrong type')
except ValueError or TypeError:
print('first')
except Exception:
print('fallback')
fallback
first
47
What happens in this example?
try:
raise KeyError('key')
except (KeyError, IndexError):
raise ValueError('converted')
except ValueError:
print('second handler')
second handler is printed
KeyError propagates
ValueError propagates
48
What is printed?
class ParseError(Exception):
pass
class DetailedParseError(ParseError):
pass
try:
raise DetailedParseError()
except (ParseError, ValueError):
print('general')
except DetailedParseError:
print('detailed')
general
detailed
49
In Python 3.11 or later, what is printed by this code?
events = []
try:
raise ExceptionGroup(
'group',
[ValueError('a'), TypeError('b'), ValueError('c')]
)
except* ValueError as group:
events.append(('values', len(group.exceptions)))
except* Exception as group:
events.append(('rest', len(group.exceptions)))
print(events)
[('rest', 3)]
[('values', 1), ('rest', 2)]
[('values', 2)]
[('values', 2), ('rest', 1)]
50
In Python 3.11 or later, what happens when this code is parsed?
try:
operation()
except ValueError:
recover()
except* TypeError:
recover_group()
SyntaxError
except*
operation() runs
51
What exception results from executing raise when no exception is currently being handled?
def reroute():
raise
reroute()
TypeError
RuntimeError
Exception
SystemError
52
What is printed by this code?
class SignalError(Exception):
pass
try:
raise SignalError
except SignalError as exc:
print(exc.args)
('SignalError',)
(None,)
()
TypeError is raised
53
Which values are printed in Python 3 by this code?
try:
1 / 0
except ZeroDivisionError:
try:
raise ValueError('invalid') from None
except ValueError as exc:
print(
type(exc.__context__).__name__,
exc.__cause__,
exc.__suppress_context__
)
ZeroDivisionError None True
ZeroDivisionError None False
None None True
ZeroDivisionError ValueError True
54
What is printed by the outer handler?
try:
try:
raise ValueError('primary')
finally:
raise TypeError('cleanup')
except Exception as exc:
print(type(exc).__name__, type(exc.__context__).__name__)
ValueError TypeError
ValueError NoneType
TypeError ValueError
TypeError NoneType
55
How do the tracebacks produced by these functions differ?
def bare():
try:
1 / 0
except Exception:
raise
def named():
try:
1 / 0
except Exception as exc:
raise exc
raise adds the handler location; raise exc preserves the original traceback
raise exc removes the division location; bare raise removes the handler location
raise exc adds the explicit re-raise location; bare raise preserves the original traceback
56
What occurs when this custom exception is raised?
class Shutdown(BaseException):
pass
try:
raise Shutdown()
except Exception:
print('caught')
finally:
print('cleanup')
caught is printed, then Shutdown propagates
caught and cleanup are printed, then execution continues
cleanup is printed, then Shutdown propagates
Shutdown bypasses the entire statement
57
What does the following code print?
class HttpError(Exception):
def __init__(self, status):
self.status = status
super().__init__(f'status={status}')
exc = HttpError(404)
print(exc.args, str(exc), exc.status)
(404,) 404 status=404
('status=404',) status=404 404
('status=404',) 404 status=404
(404,) status=404 404
58
What is printed by this code?
class CodeError(Exception):
def __init__(self, code):
self.code = code
super().__init__(code)
try:
raise CodeError
except CodeError:
print('code')
except TypeError:
print('type')
code
type
59
What is printed by the outer handler?
class BrokenMessage(Exception):
def __str__(self):
raise RuntimeError('formatting failed')
try:
try:
raise BrokenMessage()
except BrokenMessage as exc:
print(exc)
except RuntimeError as exc:
print(type(exc.__context__).__name__)
formatting failed
BrokenMessage
NoneType
RuntimeError
60
What is printed after the exception's args attribute is reassigned?
class PairError(Exception):
def __init__(self, left, right):
self.left = left
self.right = right
super().__init__(left, right)
exc = PairError('a', 'b')
exc.args = ('x',)
print(str(exc), exc.left, exc.right)
x x x
x a b
('a', 'b') a b
('x',) a b
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →