Python course · Part 7: When things go wrong · lab 7 of 7
When things go wrong
Catching the failure you expected and only that one, raising your own with a message worth reading, and cleaning up whatever happens.
By the end you can
- Catch specific exceptions instead of swallowing everything
- Raise errors with messages that say what to do about them
- Guarantee cleanup runs whether or not something failed
- Decide when to handle a failure and when to let it travel
Easier if you did first
step 1 of 3
Catching the one you expected
try runs code that might fail. except catches a failure and decides what to do about it. That part everyone learns quickly.
The part that matters is which failures you catch. except ValueError catches the one you were expecting. A bare except: catches everything, including the typo in the line below, the memory running out, and the user pressing Ctrl-C. The bug then disappears into your fallback value and the program carries on with wrong data.
So: name the exception. If two can happen, name both: except (ValueError, TypeError).
Keep the try block to the line that might actually fail. Wrapping twenty lines means you no longer know which one you caught, and a mistake in any of them is now silently handled.
Write the three. A bare except will fail the checks.
# Catches everything, including your own typos:
try:
value = int(text)
except:
value = 0
# Catches what you expected:
try:
value = int(text)
except ValueError:
value = 0What these words mean
- try / except
- Run this; if it fails that way, do this instead.
- ValueError
- Right type, unusable contents.
- TypeError
- Wrong type altogether.
- ZeroDivisionError
- Divided by zero.
- KeyError
- No such key in a dictionary.
- except (A, B)
- Catch either of two.
Easy to get wrong
except:
except ValueError:
A bare except also catches your own mistakes in the same block, so a misspelled variable becomes a silent fallback rather than an error you can see and fix.
except Exception: pass
Handling it, or letting it travel
Swallowing an error without acting on it means the program continues in a state you did not plan for, and the real failure surfaces much later somewhere unrelated.
What we check
- Text that is a number converts
- Text that is not a number gives None
- A missing value gives None rather than raising TypeError
- Division works
- Dividing by zero gives None
- The answer is rounded
- An existing key comes back
- A missing key gives empty text
- An empty record is fine
- No bare except: the exceptions are named
- ValueError is caught by name
Nothing printed yet. Run your code.