raise

In Python, the raise keyword allows you to trigger exceptions manually. You can use it to generate an error when a particular condition arises in your code, allowing you to handle exceptional situations gracefully.

Python raise Keyword Examples

Here’s a quick example of using the raise keyword:

Python
>>> def divide(a, b):
...     if b == 0:
...         raise ValueError("Cannot divide by zero!")
...     return a / b
...

>>> divide(10, 2)
5.0

>>> divide(10, 0)
Traceback (most recent call last):
    ...
ValueError: Cannot divide by zero!

In this example, the divide() function checks if the divisor b is zero. If that’s the case, the function raises a ValueError exception with a custom error message. When you call divide(10, 0), the exception is triggered, and the program outputs a traceback message.

Python raise Keyword Use Cases

  • Raising exceptions to signal invalid operations or states
  • Propagating exceptions to higher levels in the program where they can be handled appropriately

Tutorial

Python's raise: Effectively Raising Exceptions in Your Code

In this tutorial, you'll learn how to raise exceptions in Python, which will improve your ability to efficiently handle errors and exceptional situations in your code. This way, you'll write more reliable, robust, and maintainable code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader