Skip to content
Forge Learn/Errors & Robustness

Exceptions: try / except / finally / raise

6 min read

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.

Basic try/except

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.

Catching a specific exception - KeyError

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.

try / except / else / finally

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.

Raising a built-in exception with a message
  • -`try`/`except`: attempt risky code, handle 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")`: signal your own failure condition, with a message explaining what went wrong.
ScaleDojo Logo
Initializing ScaleDojo