Python raise Statement: Syntax and Usage
Learn how to use Python's raise statement to raise built-in or custom exceptions, re-raise caught errors, chain exceptions with 'from', and design exception hierarchies.

The raise statement is Python's explicit way to trigger an exception. When executed, it stops the current execution flow and hands control to the nearest matching exception handler. The basic syntax is simple:
raise SomeException("message")You can raise an exception class or an instance. If you pass a class, Python instantiates it without arguments. If you pass an instance, that exact object is raised. You can also use raise with no arguments inside an except block to re-raise the currently handled exception.
Raising Built-in Exceptions
Python provides many built-in exceptions such as ValueError, TypeError, KeyError, and RuntimeError. You should raise these when they match the error condition precisely. For example, a method that expects a valid volume level might raise ValueError when the argument is invalid:
class AudioDevice:
def set_volume(self, level):
if level < 0 or level > 10:
raise ValueError("Volume must be between 0 and 10")
self.volume = levelRaising a built-in exception is appropriate when the error is generic and the caller already knows how to handle it. It avoids forcing the caller to import a custom exception type.
Raising Custom Exceptions
For domain-specific errors, define a custom exception class. This makes error handling more expressive and allows callers to catch only the errors they care about. A minimal custom exception inherits from Exception:
class ConfigurationError(Exception):
passYou can then raise it with additional context:
def load_config(path):
if not path.exists():
raise ConfigurationError(f"Config file not found: {path}")Custom exceptions are especially useful in libraries and larger applications where callers need to distinguish between different failure modes without relying on string matching.
Re-raising the Current Exception
Inside an except block, a bare raise statement re-raises the exception that was caught. This is useful when you need to log, clean up, or perform an action without swallowing the error:
try:
process_data(data)
except DataError:
logger.exception("Failed to process data")
raiseThe bare raise preserves the original traceback, which is essential for debugging. Do not use raise e unless you intentionally want to reset the traceback to the current point, which loses the original context.
Chaining Exceptions with from
When you catch one exception and raise another, use the from clause to chain them. This preserves the original exception as the __cause__ and makes the traceback show both errors:
try:
parse_json(raw)
except JSONDecodeError as exc:
raise ValidationError("Invalid payload") from excThe from clause is also useful when you want to explicitly suppress context with from None, which hides the original exception. Use from None only when the original error is irrelevant and would confuse the caller.
Common Mistakes and Pitfalls
One frequent mistake is using a bare raise outside an except block, which raises RuntimeError: No active exception to re-raise. Another is catching an exception and raising a new one without preserving the original traceback, especially when the new exception is not chained with from. Also, be careful not to catch too broadly and then raise a generic exception, as that hides the failure mode from callers.
Performance and Maintainability Considerations
Raising an exception is more expensive than a simple return because it involves unwinding the stack and constructing a traceback. However, exceptions should represent exceptional conditions, not normal control flow. Using them for expected conditions, like validating user input in a loop, can degrade performance and make the code harder to follow. For maintainability, define a clear exception hierarchy so callers can catch specific types without relying on message text.
Designing Exception Hierarchies
When building a library, create a base exception for your module and derive specific exceptions from it. For example:
class PaymentError(Exception):
pass
class InsufficientFundsError(PaymentError):
pass
class CardDeclinedError(PaymentError):
passThis lets callers catch PaymentError to handle any payment failure, or catch specific subclasses for granular handling. Avoid raising generic Exception directly, as it forces callers to catch everything.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.