The finally clause and raising exceptions
20-minute lesson · module-exceptions-04
You are previewing this course as a guest
Read anything and run any exercise you like. It all runs in your own browser, so nothing here is saved: no XP, no progress, and the AI tutor needs an account. Sign in and your work starts counting.
The finally clause and raising exceptions
20-minute lesson · module-exceptions-04
- Use a finally clause for cleanup that must run whether or not an exception occurred.
- Raise an exception with the `raise` statement to signal an error yourself.
- Choose an appropriate built-in exception type and message when raising.
- Combine raising and catching to validate inputs.
Source attribution
Status: adapted
How to Think Like a Computer Scientist: Interactive Edition — source · Exceptions / The finally clause / The raise statement
Adaptation notes. Reading rewritten in our voice. Examples use an Iowa State registration validator that raises ValueError for out-of-range credit loads. Hidden tests check that a validator raises on bad input and that finally-style cleanup always runs.
License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.