try and except
values = ["10", "20", "abc", "40"]
total = 0
for value in values:
try:
total += int(value)
except ValueError:
print("Skipping a bad value:", value)
finally:
pass # Runs every time, error or not
print("Total:", total)Output
Skipping a bad value: abc Total: 70
Without try, the program would stop at “abc”. Name the error you expect, so that surprises aren't hidden.
def set_age(age):
if age < 0:
raise ValueError("Age can't be negative")
return age
try:
set_age(-5)
except ValueError as error:
print("Problem:", error)Output
Problem: Age can't be negative
| Error | When it happens |
|---|---|
| ValueError | Right type, wrong value: int("abc") |
| TypeError | Wrong type: "a" + 1 |
| KeyError | That key isn't in the dictionary |
| IndexError | That position isn't in the list |
| ZeroDivisionError | Dividing by zero |
| FileNotFoundError | That file doesn't exist |
Finished reading?