Chapters
Python114 chapters

Exercises

Raising Exceptions

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Raise a ValueError with a helpful message when the age is negative.

Python
def set_age(age):
    return age

print(set_age(30))
try:
    set_age(-1)
except ValueError as problem:
    print("ValueError:", problem)
Exercise 2

Define a ConfigError and raise it when the name is missing.

Python
# define ConfigError

def load(settings):
    if "name" not in settings:
        pass
    return settings["name"]

try:
    load({})
except Exception as problem:
    print(type(problem).__name__)
Exercise 3

Log the failure and let the original exception continue to the caller.

Python
def load(text):
    try:
        return int(text)
    except ValueError:
        print("logging the failure")
        return None

try:
    load("abc")
    print("caller saw nothing")
except ValueError:
    print("caller still saw it")