Notice: Due to an ongoing migration of our storage and publishing system, material requested since last month will not be uploaded for the time being, and new requests are paused. All existing notes remain available.
You're offline
Unit 5 MCQsException handling
ECAP776 ·
60 questions. Pick an option to check it.
Answer: It suppresses the prior exception in the displayed traceback
from None raises the new exception while suppressing display of the original exception context.
Question 36 of 60 · Custom exception · Medium
What is printed by this code?
Python
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__)
Not quite. Try another option.
Answer: AgeError
AgeError inherits from Exception, so the handler catches it while its actual class name remains AgeError.
Question 37 of 60 · Custom exception · Medium
What does this code print?
Python
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))
Not quite. Try another option.
Answer: 120 score=120
err.score contains 120, and the message passed to Exception is returned by str(err).
Question 38 of 60 · Custom exception · Medium
Which handler catches the exception raised below?
Python
class ValidationError(Exception):
pass
class EmailError(ValidationError):
pass
raise EmailError("invalid email")
Not quite. Try another option.
Answer: except ValidationError:
EmailError inherits from ValidationError, so a handler for the parent exception catches it.
Question 39 of 60 · Custom exception · Medium
What is the value of err.args in the handler?
Python
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)
Not quite. Try another option.
Answer: ("limit=5",)
Arguments passed to Exception.__init__ are stored in the exception's args tuple.
The else suite runs because the inner try succeeds. Its KeyError is not handled by the associated except, but finally runs before the outer handler catches it.
Python clears and deletes an exception-handler target after the handler finishes. The earlier binding of err is therefore no longer available, while saved remains bound.
Question 44 of 60 · Catching exceptions · Hard
What is the result of this code?
Python
class Manager:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return 'False'
with Manager():
raise RuntimeError('failure')
print('done')
Not quite. Try another option.
Answer: It prints done
__exit__ suppresses an active exception when it returns any truthy value. The nonempty string 'False' is truthy despite its text.
ValueError or TypeError is evaluated as an ordinary expression and produces ValueError, since exception classes are truthy. It therefore does not match TypeError.
Question 47 of 60 · Catching multiple exceptions · Hard
Sibling except clauses only select a handler for an exception from the try suite. An exception raised inside the selected handler is not caught by a later sibling handler.
Question 48 of 60 · Catching multiple exceptions · Hard
What is printed?
Python
class ParseError(Exception):
pass
class DetailedParseError(ParseError):
pass
try:
raise DetailedParseError()
except (ParseError, ValueError):
print('general')
except DetailedParseError:
print('detailed')
Not quite. Try another option.
Answer: general
Handlers are tested in source order. Because DetailedParseError is a subclass of ParseError, the first tuple-based handler matches before the specific handler is reached.
Question 49 of 60 · Catching multiple exceptions · Hard
In Python 3.11 or later, what is printed by this code?
A single try statement cannot mix ordinary except clauses with except* clauses. Separate or nested try statements are required.
Question 51 of 60 · Raising exceptions · Hard
What exception results from executing raise when no exception is currently being handled?
Python
def reroute():
raise
reroute()
Not quite. Try another option.
Answer: RuntimeError
A bare raise requires an active exception to re-raise. Without one, Python raises RuntimeError indicating that no active exception exists.
Question 52 of 60 · Raising exceptions · Hard
What is printed by this code?
Python
class SignalError(Exception):
pass
try:
raise SignalError
except SignalError as exc:
print(exc.args)
Not quite. Try another option.
Answer: ()
Raising an exception class causes Python to instantiate it without arguments. The resulting SignalError therefore has an empty args tuple.
Question 53 of 60 · Raising exceptions · Hard
Which values are printed in Python 3 by this code?
Python
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__
)
Not quite. Try another option.
Answer: ZeroDivisionError None True
from None suppresses display of the implicit context but does not erase it. The context remains the ZeroDivisionError, the explicit cause is None, and suppression is enabled.
Answer: raise exc adds the explicit re-raise location; bare raise preserves the original traceback
A bare raise continues the existing traceback without adding the handler's raise statement. Raising the bound exception explicitly adds that raise location to its traceback.
Answer: Only cleanup is printed, then Shutdown propagates
Shutdown does not inherit from Exception, so that handler cannot catch it. It still inherits from BaseException, and the finally suite executes during propagation.
Question 57 of 60 · Custom exception · Hard
What does the following code print?
Python
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)
Not quite. Try another option.
Answer: ('status=404',) status=404 404
The call to super().__init__ stores the formatted string in args. With one argument, the inherited __str__ returns that argument's string, while status remains 404.
Raising the class asks Python to instantiate it with no arguments. Because CodeError.__init__ requires code, construction raises TypeError, which is caught by the second handler.
Question 59 of 60 · Custom exception · Hard
What is printed by the outer handler?
Python
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__)
Not quite. Try another option.
Answer: BrokenMessage
Printing calls the custom __str__, which raises RuntimeError. Because that happens while BrokenMessage is being handled, the original exception becomes the RuntimeError's context.
Question 60 of 60 · Custom exception · Hard
What is printed after the exception's args attribute is reassigned?
Python
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)
Not quite. Try another option.
Answer: x a b
The inherited exception string uses the current args; a one-element tuple renders as that element alone. Reassigning args does not alter the separate left and right attributes.
That's unit 5
Answer a few questions and your score shows up here.
Nearly through. Did unit 5 of ECAP776 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 5 of ECAP776 save you a night before the exam?
Then you can help keep it free for the next batch. 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.