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).
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.
Related Questions
"Every syntax error is an exception but every exception cannot be a syntax error." Justify the statement.
When are the following built-in exceptions raised? Give examples to support your answers.
- ImportError
- IOError
- NameError
- ZeroDivisionError
Use assert statement in Question No. 3 to test the division expression in the program.
Define the following:
- Exception Handling
- Throwing an exception
- Catching an exception