Exceptions · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
try:
    [1, 2, 3][10]
except LookupError as ex:
    print(type(ex).__name__)
2. What does this print?
try:
    int('abc')
except Exception:
    print('Exception')
except ValueError:
    print('ValueError')
3. Which of these is not caught by except Exception:?
4. What does this print?
def f():
    try:
        raise ValueError()
    except ValueError:
        print('a', end=' ')
    else:
        print('b', end=' ')
    print('c', end=' ')

f()
5. What does this print?
def f():
    try:
        print('try', end=' ')
        return 'result'
    finally:
        print('finally', end=' ')

print(f())
6. What does this print?
def f():
    try:
        return 1 / 0
    finally:
        return 'finally wins'

print(f())
7. What does this print?
ex = ValueError('bad', 42)
print(str(ex), ex.args[1])
8. What does this print?
try:
    try:
        {}['key']
    except KeyError:
        raise RuntimeError('lookup failed') from None
except RuntimeError as ex:
    print(ex.__cause__, type(ex.__context__).__name__, ex.__suppress_context__)
9. What does this print?
try:
    raise ExceptionGroup('batch', [
        ValueError('a'), TypeError('b'), ValueError('c'),
    ])
except* ValueError as eg:
    print('V', len(eg.exceptions), end=' ')
except* TypeError as eg:
    print('T', len(eg.exceptions), end=' ')
10. What does this print?
ex = ValueError('bad value')
ex.add_note('while reading row 3')
print(str(ex), '|', ex.__notes__)
11. What does this print?
class AppError(Exception):
    """base"""

class MissingKey(AppError, KeyError):
    """a key is missing"""

try:
    raise MissingKey('id')
except LookupError:
    print('LookupError handler')
except AppError:
    print('AppError handler')
12. Which statement about try in Python 3.11+ is correct?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: try, except, else and finally

Write run_task(task, log). It calls task() (a function with no arguments) and records what happens by appending strings to the list log:

1. 'start' before calling the task. 2. 'ok' if the task finished without raising, and then return the task's result. 3. 'failed: <ExceptionTypeName>' (for example 'failed: ZeroDivisionError') if the task raised an Exception, and then re-raise the same exception so the caller still sees it. 4. 'done' at the very end, in every case.

So a successful task produces ['start', 'ok', 'done'], and a failing one ['start', 'failed: ...', 'done'].

Hints (3)
  1. Put only task() in the try block. The success bookkeeping belongs in else, the cleanup in finally.
  2. type(ex).__name__ gives the class name. A bare raise inside the except block re-raises the current exception.
  3. return result inside else is fine: finally still runs before the function actually returns.
Show a solution
def run_task(task, log):
    log.append('start')
    try:
        result = task()
    except Exception as ex:
        log.append(f'failed: {type(ex).__name__}')
        raise
    else:
        log.append('ok')
        return result
    finally:
        log.append('done')

Exercise 2: Translate and chain exceptions

Settings are stored in a dict of strings, e.g. {'port': '8080'}. Write:

- SettingError, a custom exception derived from Exception. - MissingSettingError and InvalidSettingError, both derived from SettingError. - get_int_setting(config, key), which returns int(config[key]), but: - if the key is missing, raises MissingSettingError(f'missing setting: {key}') from None (the KeyError is an implementation detail); - if the value isn't a valid integer, raises InvalidSettingError(f'invalid integer for {key}: {value!r}') chained from the original ValueError, so the cause is kept.

Hints (2)
  1. Use two separate try blocks, one around config[key] and one around int(value), so you know which step failed.
  2. raise NewError(...) from None hides the context; raise NewError(...) from ex sets __cause__.
Show a solution
class SettingError(Exception):
    """Base exception for settings."""

class MissingSettingError(SettingError):
    """A required setting is missing."""

class InvalidSettingError(SettingError):
    """A setting has an invalid value."""

def get_int_setting(config, key):
    try:
        value = config[key]
    except KeyError:
        raise MissingSettingError(f'missing setting: {key}') from None
    try:
        return int(value)
    except ValueError as ex:
        raise InvalidSettingError(f'invalid integer for {key}: {value!r}') from ex

Exercise 3: An exception hierarchy with data

Build the exceptions for a small banking app:

- BankError(Exception): the base class. - AccountFrozenError(BankError). - InsufficientFundsError, which must be a BankError and a ValueError (so generic ValueError handlers catch it). Its constructor is InsufficientFundsError(balance, amount). It stores both as attributes, has a shortfall property (amount - balance), and its str() is 'cannot withdraw 150, balance is 100' (for balance 100, amount 150). Its args must be (message,).

Then write withdraw(account, amount) for an account dict like {'balance': 100, 'frozen': False}: raise AccountFrozenError('account is frozen') if frozen, raise InsufficientFundsError if the amount exceeds the balance, otherwise subtract the amount and return the new balance.

Hints (3)
  1. List both base classes: class InsufficientFundsError(BankError, ValueError):.
  2. In __init__, store the attributes, then call super().__init__(message) with the formatted message so args and str() work.
  3. Check for problems before changing the balance.
Show a solution
class BankError(Exception):
    """Base exception for the bank app."""

class AccountFrozenError(BankError):
    """The account is frozen."""

class InsufficientFundsError(BankError, ValueError):
    """Not enough money in the account."""

    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f'cannot withdraw {amount}, balance is {balance}')

    @property
    def shortfall(self):
        return self.amount - self.balance

def withdraw(account, amount):
    if account['frozen']:
        raise AccountFrozenError('account is frozen')
    if amount > account['balance']:
        raise InsufficientFundsError(account['balance'], amount)
    account['balance'] -= amount
    return account['balance']

Exercise 4: Report every error at once

Write parse_numbers(items), which converts every string in items with float() and returns the list of results.

Instead of stopping at the first bad item, it must try all of them. If any fail, raise an ExceptionGroup with the message 'N invalid numbers' (N is the number of failures) containing each ValueError raised by float(), in order. Before collecting each error, attach a note with add_note of the form item 2: 'abc' (the position in items, starting at 0, and the repr of the item).

Hints (3)
  1. Loop with enumerate and wrap each float(item) in its own try, appending failures to an errors list.
  2. ex.add_note(...) must be called on the exception object before you store it.
  3. After the loop: if errors: raise ExceptionGroup(f'{len(errors)} invalid numbers', errors).
Show a solution
def parse_numbers(items):
    results = []
    errors = []
    for i, item in enumerate(items):
        try:
            results.append(float(item))
        except ValueError as ex:
            ex.add_note(f'item {i}: {item!r}')
            errors.append(ex)
    if errors:
        raise ExceptionGroup(f'{len(errors)} invalid numbers', errors)
    return results