How to use raise keyword in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
The raise keyword is how Python signals that execution cannot continue normally. Used well, it makes function contracts clearer and failures easier to debug. Used badly, it creates vague errors, hides root causes, or turns normal control flow into exception-heavy code.
Raise Specific Exceptions
The first rule is to raise an exception type that matches the failure. Standard exception classes already cover many common cases.
Use TypeError for wrong types, ValueError for bad values, KeyError for missing mapping keys, and so on. A precise exception tells the caller what kind of mistake happened before they even read the message.
Define Custom Exceptions for Domain Logic
For business rules, custom exception classes make the code easier to understand and easier to catch selectively.
Now callers can catch BillingError without swallowing unrelated runtime failures. That is much better than raising plain Exception everywhere.
Use raise ... from to Preserve the Cause
Sometimes you catch a low-level exception and want to replace it with a clearer higher-level one. When you do that, keep the original cause.
The from exc part preserves the exception chain. That makes tracebacks much more informative in logs and production incidents. Without it, the original parsing failure disappears and you lose useful debugging context.
Re-Raise the Current Exception When You Only Need Cleanup
Inside an except block, plain raise means "throw the same exception again." That is the right choice when you need to log, count metrics, or clean up resources without changing the error itself.
Compare that with raise NewError(...), which replaces the current exception. Replacing every exception automatically is usually a mistake because it throws away detail that the caller or log reader may need.
Raise at Boundaries, Not in Every Tiny Branch
Good exception design usually validates bad input near the system boundary, then lets the rest of the code assume valid data. That is cleaner than scattering raise checks through every internal loop.
For example:
- validate API request data when it first enters the service
- validate file format after parsing, not deep in business logic
- raise immediately when invariants are broken
This style keeps the error contract easy to reason about. It also reduces the chance of invalid values leaking deeper into the program and failing in confusing ways later.
Test Exception Behavior Explicitly
Exception behavior is part of a function's public contract, so it should be tested like any other output.
Testing the exception type and part of the message makes it harder for regressions to slip through unnoticed.
When Not to Use raise
Exceptions are for exceptional or invalid states, not for everyday branching in performance-sensitive code. If a missing value is a normal case, returning None, an empty list, or a typed result object may be clearer than raising an exception. Overusing exceptions for routine control flow makes the code noisy and harder to profile.
That does not mean exceptions are expensive in every practical sense. It means they should communicate failure, not replace basic boolean logic.
Common Pitfalls
The biggest mistake is raising generic Exception for everything. Another is replacing a low-level exception with a new one and forgetting from, which destroys the causal chain. Developers also catch exceptions too broadly and then continue as if nothing happened, which hides bugs instead of handling them. Finally, some code uses exceptions as ordinary branching logic, which makes intent less clear and error handling harder to test.
Summary
- Raise specific exception types that match the failure.
- Use custom exception classes for domain-specific rules.
- Preserve original causes with
raise ... from. - Use plain
raiseto rethrow the current exception after cleanup or logging. - Treat exception behavior as part of the function contract and test it explicitly.
Related reading
- How to use request_id while logging in asynchronous functions?
- How to use string.replace in python 3.x
- How to use subprocess command with pipes
- How to use TensorFlow in OOP style?
- How to use tensorflow debugging tool tfdbg on tf.estimator in Tensorflow?
- How to use the CancellationToken without throwing/catching an exception?
- How to use TensorFlow metrics in Keras
- How to use tensorflow on spyder?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.