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!")
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!
Must Read:
Documentation: https://docs.python.org/3/tutorial/errors.html?highlight=raise
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!