Pythonadvanced 8 min
try, except, else, finally and raise: handle problems gracefully and raise your own.
How to catch errors with try / except, run cleanup with finally, raise your own errors and create custom exception classes.
Bad input, missing files and network drops are normal. A program that handles them can recover or explain the problem, instead of printing a long traceback and stopping.
When something goes wrong, Python raises an exception. If nothing handles it, the program stops with a traceback. You handle it with:
except runs only if that kind of exception happened. Catch specific exceptions, not everything.else runs only when no exception occurred.finally always runs, which is perfect for cleanup.except ValueError as e: and str(e).raise ValueError("message").ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, FileNotFoundError.Exception.NegativeAgeError is a custom exception, a class that inherits from Exception.parse_age("30") works, so else runs: 30 -> ok 30. Then finally prints checked 30.int("abc") raises ValueError, which prints abc -> not a number.-5 converts fine but we raise NegativeAgeError, caught by the second except: -5 -> Age cannot be negative.finally runs every time.ZeroDivisionError. The message is division by zero.Add a rule that ages over 150 raise a ValueError("too old") and test it with "200".
except: that hides every problem, even typos and Ctrl+C.try. Keep it small.pass. Log or handle them.try / except / else / finally handle exceptions; raise creates them.try blocks small.Exception for custom errors.Next: splitting code into modules.
try:
risky()
except ValueError:
print("bad value")
else:
print("no problem")
finally:
print("always runs")class NegativeAgeError(Exception):
pass
def parse_age(text):
age = int(text)
if age < 0:
raise NegativeAgeError("Age cannot be negative")
return age
for value in ["30", "abc", "-5"]:
try:
age = parse_age(value)
except ValueError:
print(value, "-> not a number")
except NegativeAgeError as e:
print(value, "->", e)
else:
print(value, "-> ok", age)
finally:
print("checked", value)
try:
print(10 / 0)
except ZeroDivisionError as e:
print("Error:", e)