So far, you have learned to catch errors with
Instead of silently returning a bad value or crashing later, Python lets you stop execution immediately by raising your own exception. This tells every caller, "the input was invalid; I am giving up." The message you attach to the exception becomes part of the traceback.
try and except. But sometimes the error is not a surprise. It is something you know about in advance: an argument that cannot be right.Instead of silently returning a bad value or crashing later, Python lets you stop execution immediately by raising your own exception. This tells every caller, "the input was invalid; I am giving up." The message you attach to the exception becomes part of the traceback.
raise with a clear message
def divide(a, b):
if b == 0:
raise ValueError("b must not be zero")
return a / b
print(divide(10, 2)) # 5.0
# divide(10, 0) would raise the ValueError above.raise takes an exception object. The most common built-in types are ValueError, TypeError, and KeyError. Pick the one whose name best describes what went wrong, then pass a short human-readable string. That string is what shows up in tracebacks, so write it like you would explain to another developer.Validating arguments
def set_temperature(celsius):
if not isinstance(celsius, (int, float)):
raise TypeError("need a number")
if celsius < -273.15 or celsius > 1000:
raise ValueError("out of range")
return f"{celsius} C"
print(set_temperature(20)) # 20 C
# set_temperature('hot') raises TypeErrorLetting it travel up
def inner(x):
if x < 0:
raise ValueError("no negatives")
return x * 2
def outer(x):
# no try/except here: errors keep climbing
return inner(x) + 1
print(outer(3)) # 7
# outer(-5): the traceback shows both functionsYou do not have to catch an exception at the level where it is raised. It bubbles up through
inner, then outer, and so on, until a try/except catches it, or the program stops with a traceback. This keeps low-level functions simple: they validate their own inputs and let higher layers decide how (or whether) to recover.