When things go sideways.
Handle an expected failure without hiding the useful evidence.
01 The idea
An exception interrupts the normal flow when an operation fails. Use try and except to handle failures you expect and know how to recover from. Catch specific exception types so unrelated programming mistakes remain visible.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
raw_minutes = "later"
try:
minutes = int(raw_minutes)
except ValueError:
print("Please enter a whole number.")
else:
print(f"Scheduled for {minutes} minutes")Please enter a whole number.
03 Under the hood
- 1
int() cannot interpret "later" as an integer, so it raises ValueError. The except block provides a helpful response.
- 2
else runs only if the try block finishes without an exception. finally, when present, runs as the statement exits, whether it succeeded or failed.
- 3
Keep the try block narrow. It should be obvious which operation is expected to fail. Use raise ValueError(...) when your own function receives an invalid value it cannot reasonably use.
04 Your turn, builder
Convert "12.5" using float(), catch ValueError, and print the converted number when conversion succeeds.
Reveal one possible solution +
try:
value = float("12.5")
except ValueError:
print("Not a number")
else:
print(value)05 Check your signal
When does the else block of try/except run?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.