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 except block
B. The else block
C. The try block
D. The finally block

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Catching multiple exceptions Easy
A. A randomly selected block
B. The last matching block
C. Every matching block
D. The first 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. except
B. raise
C. trigger
D. assertion

12 Which statement raises a built-in ValueError?

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

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

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

14 Why might a function explicitly raise an exception?

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

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

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

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

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

17 Which definition correctly creates a custom exception named InvalidAgeError?

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

18 How is a custom exception named InvalidAgeError triggered?

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

19 Which handler catches a custom exception named InvalidAgeError?

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

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

Custom exception Easy
A. It removes the need for handlers
B. It prevents all built-in exceptions
C. It identifies an application-specific error
D. It automatically corrects every 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. 3
B. 3.5
C. ValueError
D. -1

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. 5 followed by error
C. error followed by done
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. TypeError
C. Exception
D. python

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. ZeroDivisionError only
B. cleanup followed by 0
C. cleanup followed by 2
D. 2 followed by cleanup

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 ZeroDivisionError is propagated
C. Both exceptions are fully handled
D. A ValueError remains unhandled

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. Both handlers in order
B. The FileNotFoundError handler
C. The OSError handler
D. Neither exception handler

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 bad
B. bad ok
C. ok ok
D. ok bad

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 TypeError is propagated
B. None is printed
C. A KeyError is propagated
D. handled is printed

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. return ValueError("negative quantity")
C. raise ValueError("negative quantity")
D. raise TypeError("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. ValueError propagates without printing anything
B. RuntimeError replaces the original exception
C. logged is printed and execution continues
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 original ValueError object
B. The string conversion failed
C. The new RuntimeError 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 prevents the ValueError from being raised
B. It suppresses the prior exception in the displayed traceback
C. It converts the prior exception into a warning
D. It catches both exceptions before termination

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. ValueError
B. AgeError
C. Exception
D. invalid age

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. 120 ScoreError
B. ScoreError score=120
C. 120 score=120
D. score=120 120

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 KeyError:
B. except ArithmeticError:
C. except ValidationError:
D. except TypeError:

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. 30
B. -30
C. 50
D. 80

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', 'inner', 'finally', 'outer']
B. ['try', 'else', 'outer', 'finally']
C. ['try', 'else', 'finally']
D. ['try', 'else', '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 UnboundLocalError
B. It prints outer inner
C. It prints inner inner
D. It raises NameError

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 raises TypeError
C. It prints False
D. It prints done

45 What occurs when this code runs?

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

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

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. Both lines are printed
B. fallback
C. first
D. A syntax error occurs

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. second handler is printed
B. The original KeyError propagates
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. general
B. The exception propagates
C. detailed
D. Both lines are printed

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. [('rest', 3)]
B. [('values', 1), ('rest', 2)]
C. [('values', 2)]
D. [('values', 2), ('rest', 1)]

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 treats both clauses as except*
C. It fails only when operation() runs
D. It handles either exception form

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

PYTHON
def reroute():
    raise

reroute()

Raising exceptions Hard
A. TypeError
B. RuntimeError
C. Exception
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. (None,)
C. ()
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. ZeroDivisionError None True
B. ZeroDivisionError None False
C. None None True
D. ZeroDivisionError ValueError 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. ValueError TypeError
B. ValueError NoneType
C. TypeError ValueError
D. TypeError 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. caught and cleanup are printed, then execution continues
C. Only cleanup is printed, then Shutdown propagates
D. Nothing is printed because Shutdown bypasses the entire statement

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,) 404 status=404
B. ('status=404',) status=404 404
C. ('status=404',) 404 status=404
D. (404,) status=404 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. Both lines are printed
B. Nothing is printed
C. code
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. formatting failed
B. BrokenMessage
C. NoneType
D. RuntimeError

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 x x
B. x a b
C. ('a', 'b') a b
D. ('x',) a b