Editor

Exceptions: What Does This Print

What does this print? · Advanced · about 10 min

Read each short program and type exactly what it prints, with each printed line on its own line. If a program stops with an error, type the error's name, like TypeError.

Example

try:
    print(int("7"))
except ValueError:
    print("bad")

prints

7
  1. Program 1

    try:
        x = int("12")
    except ValueError:
        print("bad")
    else:
        print("good", x)
    finally:
        print("end")
  2. Program 2

    try:
        x = int("twelve")
        print("converted")
    except ValueError:
        print("bad")
    finally:
        print("end")
  3. Program 3

    def f():
        try:
            return "try"
        finally:
            print("cleanup")
    print(f())
  4. Program 4

    try:
        [1, 2][5]
    except KeyError:
        print("key")
  5. Program 5

    class TooBig(Exception):
        pass
    try:
        raise TooBig("over 100")
    except ValueError:
        print("value")
    except TooBig as e:
        print("caught:", e)
  6. Program 6

    def check(n):
        if n < 0:
            raise ValueError("negative")
        return n
    try:
        print(check(5))
        print(check(-1))
        print(check(3))
    except ValueError as e:
        print("error:", e)
  7. Program 7

    try:
        try:
            int("x")
        except ValueError:
            print("inner")
            raise
    except ValueError:
        print("outer")
  8. Program 8

    try:
        x = 1 / 0
    except ZeroDivisionError:
        print(y)