When Python cannot continue, it raises an exception. An uncaught exception stops the program and prints a traceback.
Common types:
| Exception | Cause |
|---|---|
ValueError |
Right type, wrong value. int("abc") |
TypeError |
Wrong type. "a" + 1 |
KeyError |
Missing dictionary key |
IndexError |
Index past the end of a list |
FileNotFoundError |
Opening a file that does not exist |
ZeroDivisionError |
Dividing by zero |
Catching
values = ["120", "abc", "45"]
for value in values:
try:
print(int(value))
except ValueError:
print("skipping", value)
Catch the specific exception you expect. A bare except: hides real bugs,
including typos in your own code.
else and finally
else runs when no exception was raised. finally always runs.
try:
depth = int("120")
except ValueError:
print("bad value")
else:
print("parsed", depth)
finally:
print("done")
Raising
Raise an exception when a function is given something it cannot handle.
def gc_content(sequence):
if not sequence:
raise ValueError("sequence is empty")
gc = sequence.count("G") + sequence.count("C")
return gc / len(sequence)
try:
gc_content("")
except ValueError as error:
print("error:", error)
Task
Write safe_ratio(values). It receives a list of strings. Convert each to an
integer, sum them, and return the sum divided by the count, rounded to 2
decimals.
Skip any string that is not a whole number. If nothing valid remains, return
the string "no valid values".
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 120 abc 45 | 82.5 |
| 2 | stdin | abc def | no valid values |
| 3 | stdin | 10 20 30 | 20.0 |
Hints · 2
01Hint
Collect the valid numbers in a list first, then decide what to return.
02Hint
Catching ValueError around int() is enough; no other exception applies.