KnowledgeBoat Logo
|

Computer Science

What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).

Python Exception Handling

10 Likes

Answer

The raise statement is used to throw an exception during the execution of a program.

numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
if denominator == 0:
    raise ZeroDivisionError("Error: Denominator cannot be zero.")
else: 
    quotient = numerator / denominator
    print("Quotient:", quotient)
Output
Enter the numerator: 25
Enter the denominator: 5
Quotient: 5.0

Enter the numerator: 2
Enter the denominator: 0
Traceback (most recent call last):
  File "c:\PythonPlayground\q3.py", line 4, in <module>
    raise ZeroDivisionError("Error: Denominator cannot be zero.")
ZeroDivisionError: Error: Denominator cannot be zero.

Answered By

5 Likes


Related Questions