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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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