Python Fundamentals ยท Objects, Errors and Generators
Catch errors so the program keeps going, run clean-up code no matter what, and raise your own errors for bad input.
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
result = None # handled: the program keeps going
finally:
print("checked", a, "/", b) # runs whether or not there was an error
return result
def parse_age(text):
age = int(text)
if age < 0:
raise ValueError("age cannot be negative")
return age
x = safe_divide(10, 2)
y = safe_divide(1, 0)
try:
parse_age("-3")
except ValueError as error:
message = str(error)
print(x, y, message)safe_divide(). Its body does not run yet: it runs each time the function is called.parse_age(). Its body does not run yet: it runs each time the function is called.try:.result.try:.except ZeroDivisionError:.result.try:.parse_age(), with text = '-3'. It gets its own names.age is created with the value -3.age < 0 to decide which way the code goes.parse_age() has finished, so its names are gone.error.message is created with the value 'age cannot be negative'. error goes out of scope and disappears.