Unit 5: Exception handling - Practice Quiz

ECAP776 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 Which Python block contains code that might cause an exception?

Catching exceptions Easy
A. The try block
B. The except block
C. The finally block
D. The else block

2 Which exception is raised when a number is divided by zero?

Catching exceptions Easy
A. ZeroDivisionError
B. IndexError
C. ValueError
D. TypeError

3 Which block normally runs whether or not an exception occurs?

Catching exceptions Easy
A. The try block
B. The else block
C. The finally block
D. The except block

4 When does the else block of a try statement run?

Catching exceptions Easy
A. When no exception occurs
B. Before the try block
C. After the finally block
D. When any exception occurs

5 In except ValueError as error:, what does error represent?

Catching exceptions Easy
A. The returned value
B. The exception object
C. The protected function
D. The exception class

6 Which syntax catches both ValueError and TypeError in one handler?

Catching multiple exceptions Easy
A. except (ValueError, TypeError):
B. except ValueError and TypeError:
C. except ValueError or TypeError:
D. except [ValueError, TypeError]:

7 How can different exception types be given different handling code?

Catching multiple exceptions Easy
A. Use separate except blocks
B. Use separate finally blocks
C. Use repeated try keywords
D. Use nested else blocks

8 When catching related exception classes, which handler should usually appear first?

Catching multiple exceptions Easy
A. The shortest handler
B. The final handler
C. The more specific handler
D. The more general handler

9 If several except blocks could match an exception, which matching block runs?

Catching multiple exceptions Easy
A. The first matching block
B. The last matching block
C. A randomly selected block
D. Every matching block

10 Which statement correctly handles either a conversion error or an invalid operand type?

Catching multiple exceptions Easy
A. except {ValueError, TypeError}:
B. except (ValueError + TypeError):
C. except ValueError, TypeError:
D. except (ValueError, TypeError):

11 Which keyword is used to deliberately trigger an exception in Python?

Raising exceptions Easy
A. trigger
B. raise
C. except
D. assertion

12 Which statement raises a built-in ValueError?

Raising exceptions Easy
A. return ValueError()
B. catch ValueError()
C. except ValueError()
D. raise ValueError()

13 What does a bare raise statement do inside an except block?

Raising exceptions Easy
A. Creates a custom exception
B. Re-raises the current exception
C. Returns the current exception
D. Ignores the current exception

14 Why might a function explicitly raise an exception?

Raising exceptions Easy
A. To rename a variable
B. To report invalid input
C. To repeat valid input
D. To import a module

15 Which statement raises an exception with the message Age cannot be negative?

Raising exceptions Easy
A. raise ValueError("Age cannot be negative")
B. print ValueError("Age cannot be negative")
C. return ValueError("Age cannot be negative")
D. except ValueError("Age cannot be negative")

16 Which built-in class should a basic custom exception normally inherit from?

Custom exception Easy
A. Exception
B. module
C. function
D. object

17 Which definition correctly creates a custom exception named InvalidAgeError?

Custom exception Easy
A. class InvalidAgeError(exception): pass
B. def InvalidAgeError(Exception): pass
C. class InvalidAgeError(Exception): pass
D. except InvalidAgeError(Exception): pass

18 How is a custom exception named InvalidAgeError triggered?

Custom exception Easy
A. return InvalidAgeError()
B. except InvalidAgeError()
C. catch InvalidAgeError()
D. raise InvalidAgeError()

19 Which handler catches a custom exception named InvalidAgeError?

Custom exception Easy
A. raise InvalidAgeError:
B. try InvalidAgeError:
C. except InvalidAgeError:
D. finally InvalidAgeError:

20 What is a main benefit of defining a custom exception?

Custom exception Easy
A. It automatically corrects every error
B. It prevents all built-in exceptions
C. It removes the need for handlers
D. It identifies an application-specific error

21 What is printed by the following code?

PYTHON
def parse_value(text):
    try:
        return int(text)
    except ValueError:
        return -1

print(parse_value("3.5"))

Catching exceptions Medium
A. -1
B. 3
C. 3.5
D. ValueError

22 What is the output of this code?

PYTHON
try:
    result = 10 // 2
except ZeroDivisionError:
    print("error")
else:
    print(result)
finally:
    print("done")

Catching exceptions Medium
A. done followed by 5
B. error followed by done
C. 5 followed by error
D. 5 followed by done

23 What is printed by the exception handler?

PYTHON
try:
    int("python")
except ValueError as err:
    print(type(err).__name__)

Catching exceptions Medium
A. ValueError
B. Exception
C. python
D. TypeError

24 What is the output of the following function call?

PYTHON
def calculate():
    try:
        return 8 / 0
    except ZeroDivisionError:
        return 2
    finally:
        print("cleanup")

print(calculate())

Catching exceptions Medium
A. 2 followed by cleanup
B. ZeroDivisionError only
C. cleanup followed by 0
D. cleanup followed by 2

25 What happens when this code is executed?

PYTHON
try:
    int("x")
except ValueError:
    print("conversion failed")
    10 / 0

Catching exceptions Medium
A. Only conversion failed is printed
B. A ValueError remains unhandled
C. Both exceptions are fully handled
D. A ZeroDivisionError is propagated

26 Which handler correctly catches either ValueError or TypeError and stores the exception in err?

Catching multiple exceptions Medium
A. except (ValueError, TypeError) as err:
B. except ValueError or TypeError as err:
C. except [ValueError, TypeError] as err:
D. except ValueError, TypeError as err:

27 Assume missing.txt does not exist. Which handler runs?

PYTHON
try:
    open("missing.txt")
except OSError:
    print("OS")
except FileNotFoundError:
    print("FILE")

Catching multiple exceptions Medium
A. The FileNotFoundError handler
B. Neither exception handler
C. The OSError handler
D. Both handlers in order

28 What does the following code print?

PYTHON
def convert(value):
    try:
        int(value)
    except (TypeError, ValueError):
        return "bad"
    return "ok"

print(convert(None), convert("7"))

Catching multiple exceptions Medium
A. bad ok
B. ok bad
C. bad bad
D. ok ok

29 What is printed by this code?

PYTHON
try:
    value = 4 / 0
except ArithmeticError:
    print("arithmetic")
except ZeroDivisionError:
    print("zero")

Catching multiple exceptions Medium
A. zero
B. arithmetic zero
C. arithmetic
D. Nothing is printed

30 What happens when this code runs?

PYTHON
try:
    data = {}
    print(data["name"])
except (ValueError, TypeError):
    print("handled")

Catching multiple exceptions Medium
A. A KeyError is propagated
B. None is printed
C. handled is printed
D. A TypeError is propagated

31 Which statement should replace the comment to reject a negative quantity with an appropriate built-in exception?

PYTHON
def set_quantity(quantity):
    if quantity < 0:
        # replacement
    return quantity

Raising exceptions Medium
A. except ValueError("negative quantity")
B. raise TypeError("negative quantity")
C. raise ValueError("negative quantity")
D. return ValueError("negative quantity")

32 What occurs when load() is called?

PYTHON
def load():
    try:
        int("invalid")
    except ValueError:
        print("logged")
        raise

load()

Raising exceptions Medium
A. logged is printed and execution continues
B. RuntimeError replaces the original exception
C. ValueError propagates without printing anything
D. logged is printed and ValueError propagates

33 After the following handler raises RuntimeError, what is stored in the new exception's __cause__ attribute?

PYTHON
try:
    int("x")
except ValueError as err:
    raise RuntimeError("conversion failed") from err

Raising exceptions Medium
A. The new RuntimeError object
B. The string conversion failed
C. The original ValueError object
D. The value None

34 Given the following class, what does raise Failure do?

PYTHON
class Failure(Exception):
    pass

raise Failure

Raising exceptions Medium
A. Causes a compile-time syntax error
B. Returns the Failure class object
C. Raises the base Exception class
D. Raises a default Failure instance

35 What is the main effect of from None in this code?

PYTHON
try:
    1 / 0
except ZeroDivisionError:
    raise ValueError("invalid result") from None

Raising exceptions Medium
A. It converts the prior exception into a warning
B. It catches both exceptions before termination
C. It suppresses the prior exception in the displayed traceback
D. It prevents the ValueError from being raised

36 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__)

Custom exception Medium
A. Exception
B. invalid age
C. ValueError
D. AgeError

37 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))

Custom exception Medium
A. score=120 120
B. ScoreError score=120
C. 120 score=120
D. 120 ScoreError

38 Which handler catches the exception raised below?

PYTHON
class ValidationError(Exception):
    pass

class EmailError(ValidationError):
    pass

raise EmailError("invalid email")

Custom exception Medium
A. except ArithmeticError:
B. except ValidationError:
C. except TypeError:
D. except KeyError:

39 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)

Custom exception Medium
A. ["limit=5"]
B. {"limit": 5}
C. ("limit=5",)
D. (5,)

40 What is printed when withdraw(80, 50) is called?

PYTHON
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)

Custom exception Medium
A. 80
B. 50
C. 30
D. -30

41 What is printed by the following code?

PYTHON
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)

Catching exceptions Hard
A. ['try', 'else', 'outer', 'finally']
B. ['try', 'else', 'finally']
C. ['try', 'else', 'finally', 'outer']
D. ['try', 'inner', 'finally', 'outer']

42 What does f() return?

PYTHON
def f():
    try:
        raise ValueError('bad')
    except ValueError:
        return 'handled'
    finally:
        return 'final'

Catching exceptions Hard
A. It raises ValueError
B. None
C. 'handled'
D. 'final'

43 What happens when this code executes?

PYTHON
err = 'outer'
try:
    raise ValueError('inner')
except ValueError as err:
    saved = str(err)

print(err, saved)

Catching exceptions Hard
A. It raises NameError
B. It prints inner inner
C. It raises UnboundLocalError
D. It prints outer inner

44 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')

Catching exceptions Hard
A. It propagates RuntimeError
B. It prints done
C. It raises TypeError
D. It prints False

45 What occurs when this code runs?

PYTHON
try:
    raise KeyboardInterrupt()
except Exception:
    print('caught')
finally:
    print('cleanup')

Catching exceptions Hard
A. Only caught is printed, then execution continues
B. caught and cleanup are printed
C. Nothing is printed because the exception propagates immediately
D. Only cleanup is printed, then the exception propagates

46 What is printed by the following code?

PYTHON
try:
    raise TypeError('wrong type')
except ValueError or TypeError:
    print('first')
except Exception:
    print('fallback')

Catching multiple exceptions Hard
A. first
B. A syntax error occurs
C. Both lines are printed
D. fallback

47 What happens in this example?

PYTHON
try:
    raise KeyError('key')
except (KeyError, IndexError):
    raise ValueError('converted')
except ValueError:
    print('second handler')

Catching multiple exceptions Hard
A. The original KeyError propagates
B. second handler is printed
C. The new ValueError propagates
D. Both exceptions are suppressed

48 What is printed?

PYTHON
class ParseError(Exception):
    pass

class DetailedParseError(ParseError):
    pass

try:
    raise DetailedParseError()
except (ParseError, ValueError):
    print('general')
except DetailedParseError:
    print('detailed')

Catching multiple exceptions Hard
A. Both lines are printed
B. The exception propagates
C. detailed
D. general

49 In Python 3.11 or later, what is printed by this code?

PYTHON
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)

Catching multiple exceptions Hard
A. [('values', 2), ('rest', 1)]
B. [('rest', 3)]
C. [('values', 2)]
D. [('values', 1), ('rest', 2)]

50 In Python 3.11 or later, what happens when this code is parsed?

PYTHON
try:
    operation()
except ValueError:
    recover()
except* TypeError:
    recover_group()

Catching multiple exceptions Hard
A. It raises SyntaxError
B. It fails only when operation() runs
C. It handles either exception form
D. It treats both clauses as except*

51 What exception results from executing raise when no exception is currently being handled?

PYTHON
def reroute():
    raise

reroute()

Raising exceptions Hard
A. Exception
B. TypeError
C. RuntimeError
D. SystemError

52 What is printed by this code?

PYTHON
class SignalError(Exception):
    pass

try:
    raise SignalError
except SignalError as exc:
    print(exc.args)

Raising exceptions Hard
A. ('SignalError',)
B. ()
C. (None,)
D. A TypeError is raised

53 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__
        )

Raising exceptions Hard
A. None None True
B. ZeroDivisionError None False
C. ZeroDivisionError ValueError True
D. ZeroDivisionError None True

54 What is printed by the outer handler?

PYTHON
try:
    try:
        raise ValueError('primary')
    finally:
        raise TypeError('cleanup')
except Exception as exc:
    print(type(exc).__name__, type(exc.__context__).__name__)

Raising exceptions Hard
A. TypeError ValueError
B. ValueError TypeError
C. TypeError NoneType
D. ValueError NoneType

55 How do the tracebacks produced by these functions differ?

PYTHON
def bare():
    try:
        1 / 0
    except Exception:
        raise



def named():
try:
1 / 0
except Exception as exc:
raise exc

Raising exceptions Hard
A. Bare raise adds the handler location; raise exc preserves the original traceback
B. Both forms always produce identical traceback frames and exception context
C. raise exc removes the division location; bare raise removes the handler location
D. raise exc adds the explicit re-raise location; bare raise preserves the original traceback

56 What occurs when this custom exception is raised?

PYTHON
class Shutdown(BaseException):
    pass

try:
    raise Shutdown()
except Exception:
    print('caught')
finally:
    print('cleanup')

Custom exception Hard
A. Only caught is printed, then Shutdown propagates
B. Nothing is printed because Shutdown bypasses the entire statement
C. caught and cleanup are printed, then execution continues
D. Only cleanup is printed, then Shutdown propagates

57 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)

Custom exception Hard
A. (404,) status=404 404
B. ('status=404',) status=404 404
C. (404,) 404 status=404
D. ('status=404',) 404 status=404

58 What is printed by this code?

PYTHON
class CodeError(Exception):
    def __init__(self, code):
        self.code = code
        super().__init__(code)

try:
    raise CodeError
except CodeError:
    print('code')
except TypeError:
    print('type')

Custom exception Hard
A. code
B. Nothing is printed
C. Both lines are printed
D. type

59 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__)

Custom exception Hard
A. RuntimeError
B. NoneType
C. BrokenMessage
D. formatting failed

60 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)

Custom exception Hard
A. ('x',) a b
B. ('a', 'b') a b
C. x a b
D. x x x