Reading — step 1 of 7
Learn
So far you've caught errors that Python raised automatically. But sometimes YOUR code is the one that needs to signal a problem. A function receives an impossible age of -5. A password is too short. A required config key is missing. The right response isn't to return a garbage value — it's to raise an exception and tell the caller exactly what went wrong.
The raise statement
raise <ExceptionType>(message) immediately stops the function and starts unwinding — looking for a matching except somewhere up the call stack. If no one catches it, the program crashes with a traceback.
Pick the right exception type
Use Python's built-in types when one fits — they communicate intent:
ValueError— value is the right TYPE but wrong CONTENT ("abc"for an int)TypeError— wrong TYPE entirely ("a" + 1)KeyError— missing dict keyIndexError— out-of-range indexFileNotFoundError— file missing (subclass ofOSError)NotImplementedError— abstract method placeholderRuntimeError— generic catch-all when nothing else fits
Custom exceptions
For your own domain, define a custom class:
Custom exceptions let callers catch your specific errors precisely:
A custom hierarchy lets you handle related errors as a group: class BankError(Exception) → class InsufficientFundsError(BankError), class FrozenAccountError(BankError). Callers can catch BankError to handle any banking failure or a specific subclass for fine control.
Re-raising — let it propagate
Sometimes you want to LOG and then re-raise so callers can still handle it:
Chain exceptions with from
When an exception is the cause of another:
The traceback shows BOTH errors with "The above exception was the direct cause of the following exception." Useful for adding context without losing the original cause.
When NOT to raise
- For control flow you can express with an if — exceptions are EXCEPTIONAL, not branching.
- For expected missing data — return
Noneor an Option-like wrapper instead. - In a hot loop where errors are frequent — exceptions are slow.
But for genuinely invalid state the function can't recover from, raising is the clean answer. Returning -1 or None from a function that should have produced a value silently masks bugs.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…