Skip to content

Exceptions, assertions, and explicit errors [ref]

Problem

  • Raise and catch ValueError when 2 falls outside the interval from 0 through 1.
  • Raise and catch a KeyError for "x".
  • Assert that 2 + 2 equals 4.
  • Catch StopIteration from an empty iterator.
  • Convert "x" to an integer, storing None after conversion fails.

Python solution

try:
    x = 2
    if not 0 <= x <= 1:
        raise ValueError("outside range")
except ValueError as error:
    str(error)  # 'outside range'

try:
    raise KeyError("x")
except KeyError as error:
    error.args  # ('x',)

assert 2 + 2 == 4

try:
    next(iter([]))
except StopIteration:
    exhausted = True
exhausted  # True

try:
    value = int("x")
except ValueError:
    value = None
value  # None