Sobes.tech
Middle

How to implement an exception block in PL/SQL? How to create a user-defined exception?

sobes.tech AI

Answer from AI

An exception block in PL/SQL is used to handle errors that may occur during code execution. It is placed at the end of an anonymous block or procedure/function after the BEGIN ... EXCEPTION ... END section.

Example of an exception handling block:

BEGIN
  -- Main code
  NULL; -- placeholder
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Data not found');
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
END;

To create a user-defined exception, declare a variable of type EXCEPTION, and then raise it using the RAISE statement.

Example of a user-defined exception:

DECLARE
  my_exception EXCEPTION; -- declaration of a user-defined exception
BEGIN
  -- Some logic
  IF some_condition THEN
    RAISE my_exception; -- raise the exception
  END IF;
EXCEPTION
  WHEN my_exception THEN
    DBMS_OUTPUT.PUT_LINE('User-defined exception handled');
END;