Exceptions and error handling
Catch the errors you can handle, let the others fail loudly and raise your own.
An exception is how Python reports that something went wrong. If nobody catches it, the program stops and prints a traceback: read it from the bottom, where the error type and message are.
try:
value = int(text)
except ValueError:
value = 0
else:
print("parsed", value)
finally:
print("always runs")exceptruns when that error happens.elseruns only if there was no error.finallyalways runs. Use it for cleanup.
Good habits
- Catch specific exceptions. A bare
except:hides bugs and even catches Ctrl+C. - Keep the
tryblock small, so you know which line failed. - Do not silence an error with
passunless you really mean it. At least log it.
Raising your own
class OutOfStock(Exception):
pass
def buy(stock, n):
if n > stock:
raise OutOfStock(f"only {stock} left")
return stock - n
try:
buy(2, 5)
except OutOfStock as e:
print("sorry:", e)NotePython style prefers asking forgiveness over permission (EAFP): try the operation and handle the error, instead of checking every condition first.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.