Catching exceptions with try / except
20-minute lesson · module-exceptions-03
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.
Catching exceptions with try / except
20-minute lesson · module-exceptions-03
- Write a try/except block to handle a runtime error without crashing.
- Catch a specific exception type rather than everything.
- Use the else clause for code that should run only when no exception occurred.
- Bind the exception object with `as` to inspect its message.
Source attribution
Status: adapted
How to Think Like a Computer Scientist: Interactive Edition — source · Exceptions / Handling exceptions with try/except
Adaptation notes. Reading rewritten in our voice. The worked example safely parses user-entered credit hours in an Iowa State enrollment theme. Hidden tests check that a function recovers from bad input and returns a sentinel rather than raising, and that it catches a specific type.
License notes. Original chapter is GNU FDL 1.3 (Brad Miller and David Ranum). No verbatim text from the original is reproduced here.