Exceptions
Objects and errors5 min readLesson 2 of 3
An exception stops the line it happened on and looks for a handler.
python
try:
value = int("not a number")
except ValueError:
value = 0
except (TypeError, KeyError) as error:
print("bad input:", error)
else:
print("parsed", value)
finally:
print("always runs")Catch the narrowest exception you can handle. A bare except hides real bugs, including the ones you would want to see.
Raise your own with a clear message:
python
def average(values):
if not values:
raise ValueError("average() needs at least one value")
return sum(values) / len(values)Use raise ... from error when translating one error into another, so the original cause stays visible.
