Exceptions: try / except / finally / raise
You'll learn to
- -Use try/except to catch and handle a runtime error instead of crashing
- -Catch specific exception types rather than everything indiscriminately
- -Raise your own exceptions with `raise` to signal a failure to the caller
So far, any runtime error, dividing by zero, looking up a missing dictionary key, indexing past the end of a list, has crashed the whole program. Exceptions are Python's mechanism for handling those errors gracefully: catching them, recovering, or deliberately raising your own when something your code considers invalid happens.
try / except
Code that might fail goes inside a try block. If an exception occurs, Python immediately jumps to the matching except block instead of crashing the program.
Catching Specific Exception Types
You can and should catch the specific exception type you expect, rather than a bare except: that swallows everything, including bugs you would actually want to know about, like a TypeError from a typo.
A bare except: (or except Exception:) catches everything, including errors you did not anticipate and did not actually intend to hide, like a typo'd variable name raising a NameError. Always catch the narrowest, most specific exception type that matches the failure you are actually handling.
else and finally
A try statement can have two more optional clauses: else, which runs only if no exception occurred, and finally, which always runs, whether an exception happened or not, useful for cleanup that must happen no matter what.
Raising Your Own Exceptions
The raise statement lets your own code signal that something has gone wrong, using either a built-in exception type or a custom one (covered in the next chapter). Always include a clear message. A future reader (often you, weeks later) will thank you.
- -try/except attempts risky code, handling specific failures without crashing.
- -else runs only when the try block succeeded with no exception.
- -finally always runs: success, failure, or even a return inside the try block.
- -raise SomeException("message") signals your own failure condition, with a message explaining what went wrong.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!