§ 2.7section 15 of 18·~4 min
Errors and exceptions
Real data is messy, and one bad row shouldn't crash a nightly job. try and except let you catch an error and decide what to do about it.
raw_amounts = ["499", "1299", "N/A", "250"]
clean, bad = [], []
for raw in raw_amounts:
try:
clean.append(int(raw))
except ValueError:
bad.append(raw)
print(clean)
print(bad)
OUTPUT
[499, 1299, 250]
['N/A']| Error | Usually means |
|---|---|
ValueError | Right type, bad value: int("N/A") |
KeyError | A dict key is missing |
TypeError | Wrong type: "a" + 1 |
FileNotFoundError | The file path doesn't exist |
watch out Catch specific errors like except ValueError, not a bare except:. A bare except also hides real bugs, such as a typo in a variable name.