Embercode
✕
Object-Oriented ProgrammingQuick quiz

Exceptions

6 questions. Covers Exceptions in class design in Python.

Questions 1 to 5 of 6

  1. 1. Predict the output of this program. ``python def check(x): try: if x < 0: raise ValueError(f"negative: {x}") return x * 2 except ValueError as err: print("caught", err) return -1 finally: print("finally", x) print(check(4)) print(check(-2)) ``
  2. 2. Predict the output of this program. The transfer method checks everything before it changes any balance. ``python class Account: def __init__(self, balance): self.balance = balance def transfer(self, to, amount): if amount <= 0: raise ValueError("bad amount") if amount > self.balance: raise RuntimeError(f"short by {amount - self.balance}") self.balance -= amount to.balance += amount a = Account(100) b = Account(0) try: a.transfer(b, 30) a.transfer(b, 500) except RuntimeError as err: print(err) print(a.balance, b.balance) ``
  3. 3. A caller passes a negative withdrawal amount, which is a mistake in the caller's code. Following the lesson, which exception fits?
  4. 4. A function raises an exception, and its caller does not catch it. What happens in Python? ``python def withdraw(amount): if amount < 0: raise ValueError("negative amount") return amount withdraw(-1) print("not reached") ``
  5. 5. Put these steps in the order that Python follows after a function raises an exception.

    Use the arrows to put the steps in order.

    1. 1.Python looks for a matching except block in the current function
    2. 2.If no handler is found anywhere, Python prints a traceback and stops the program
    3. 3.If no except block matches, Python leaves the function and looks in the caller
    4. 4.The normal flow stops, and the code after the raise does not run

4 question(s) left on this page.