Manually Throw an Exception in Python (raise:)


If you want to throw an exception manually in your Python code you can make use of the raise statement.


Example:
raise Exception("Throwing exception manually!")

Note: It is not recommended to throw generic Exception but its specific types such as ValueError.


Example 1:
def divide_numbers(num1, num2):
    if num2 == 0:
        raise ValueError("Divisor cannot be zero!")
    return num1 / num2

try:
    num1 = float(input("Enter the numerator: "))
    num2 = float(input("Enter the denominator: "))
    result = divide_numbers(num1, num2)
    print("Result:", result)
except ValueError as e:
    print("Error:", str(e))

Output:
Enter the numerator: 10
Enter the denominator: 0
Error: Divisor cannot be zero!


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap