Exercises
Raising Exceptions
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
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)Check first, then raise.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
print(set_age(30))
try:
set_age(-1)
except ValueError as problem:
print("ValueError:", problem)Exercise 2Passed
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__)A class inheriting from Exception with nothing in it is complete.
class ConfigError(Exception):
pass
def load(settings):
if "name" not in settings:
raise ConfigError("no name in the configuration")
return settings["name"]
try:
load({})
except Exception as problem:
print(type(problem).__name__)Exercise 3Passed
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")A bare raise inside an except re-raises the original.
def load(text):
try:
return int(text)
except ValueError:
print("logging the failure")
raise
try:
load("abc")
print("caller saw nothing")
except ValueError:
print("caller still saw it")