Handling division by zero exception in PL/SQL
PL/SQL Exception Handling: Exercise-1 with Solution
Write a PL/SQL block to handle the exception when a division by zero occurs.
Sample Solution:
PL/SQL Code:
-- PL/SQL block to handle the exception when a division by zero occurs
DECLARE
dividend NUMBER := 10;
divisor NUMBER := 0;
result NUMBER;
BEGIN
BEGIN
result := dividend / divisor;
DBMS_OUTPUT.PUT_LINE('Result: ' || result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Error: Division by zero');
END;
END;
Sample Output:
Error: Division by zero
Explanation:
The said code in Oracle's PL/SQL when executes that displays the error message if there are any exception found.
Three variables dividend, divisor, and result are declared. The dividend is initialized with the value 10, and the divisor is initialized with 0, which will cause a division by zero exception.
A nested BEGIN-END block that allows to catch the specific exception obtained from a division operation, and perform the division operation dividend / divisor and assign the result to the result variable. Since the divisor is zero, a division by zero exception raised.
The EXCEPTION block immediately follows the division operation and the ZERO_DIVIDE exception raised as specified in the block.
Inside the EXCEPTION block the DBMS_OUTPUT.PUT_LINE procedure displays an error message indicating that a division by zero has occurred.
Flowchart:
Previous: PL/SQL Exception Handling Exercises Home.
Next: Handling NO_DATA_FOUND exception in PL/SQL.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/plsql-exercises/exception-handling/plsql-exception-handling-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics