How to manually raising (throwing) an exception in Python?

Better Stack Team
Updated on January 26, 2023

To manually raise an exception in Python, use the raise statement. Here is an example of how to use it:

 
def calculate_payment(amount, payment_type):
    if payment_type != "Visa" and payment_type != "Mastercard":
        raise ValueError("Payment type must be Visa or Mastercard")
    # Do the calculation using the provided amount and payment type
    # ...

try:
    calculate_payment(100, "Discover")
except ValueError as e:
    print(e)

In this example, the calculate_payment function raises a ValueError exception if the payment_type is not either "Visa" or "Mastercard". The try-except block catches the exception and prints the error message.

You can raise any exception type that you want by specifying the exception type as the first argument to the raise statement. For example, to raise a TypeError exception, you can use the following code:

 
raise TypeError("This is a TypeError exception")

Keep in mind that it is generally a good idea to only raise exceptions in exceptional circumstances. In most cases, it is better to use standard Python control structures (such as if-else or for loops) to handle error conditions.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →