Triggering and Catching an Exception
In this step, you will learn how to handle runtime errors, known as exceptions. An unhandled exception will immediately terminate your function. You will first create a function that fails, and then modify it to catch the exception gracefully.
Let's create a function simple_divide that performs integer division. This function has a potential flaw: it will crash if you try to divide by zero.
CREATE OR REPLACE FUNCTION simple_divide(numerator INTEGER, denominator INTEGER)
RETURNS INTEGER AS $$
BEGIN
RETURN numerator / denominator;
END;
$$ LANGUAGE plpgsql;
First, call the function with valid inputs to confirm it works correctly:
SELECT simple_divide(10, 2);
The output will be the result of the division:
simple_divide
---------------
5
(1 row)
Now, call the function with a zero denominator to trigger an exception:
SELECT simple_divide(10, 0);
This command will fail and return an error message. The function execution is aborted.
ERROR: division by zero
CONTEXT: PL/pgSQL function simple_divide(integer,integer) line 3 at RETURN
This is an unhandled exception. To prevent the function from crashing, you can use an EXCEPTION block. Let's create a new function safe_divide that includes error handling.
CREATE OR REPLACE FUNCTION safe_divide(numerator INTEGER, denominator INTEGER)
RETURNS INTEGER AS $$
BEGIN
RETURN numerator / denominator;
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE 'Error: Cannot divide by zero.';
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Here's how the EXCEPTION block works:
BEGIN...END;: This defines a block of code.
EXCEPTION: This keyword starts the exception handling section.
WHEN division_by_zero THEN: This specifies that the following code should run only when a division_by_zero error occurs.
- The code inside the handler raises a notice and returns
NULL instead of crashing.
Now, call the new safe_divide function with a zero denominator:
SELECT safe_divide(10, 0);
This time, the function does not crash. It catches the exception, displays your custom notice, and returns NULL.
NOTICE: Error: Cannot divide by zero.
safe_divide
-------------
(1 row)
You have successfully caught a specific exception and controlled the function's output.