Search This Blog

Thursday, February 10, 2022

Oracle / PLSQL: Named System Exceptions

 

Oracle / PLSQL: Named System Exceptions

This Oracle tutorial explains how to use Named System Exceptions in Oracle/PLSQL with syntax and examples.

What is a named system exception in Oracle?

Named system exceptions are exceptions that have been given names by PL/SQL. They are named in the STANDARD package in PL/SQL and do not need to be defined by the programmer.

Oracle has a standard set of exceptions already named as follows:

Oracle Exception NameOracle Error
DUP_VAL_ON_INDEXORA-00001
TIMEOUT_ON_RESOURCEORA-00051
TRANSACTION_BACKED_OUTORA-00061
INVALID_CURSORORA-01001
NOT_LOGGED_ONORA-01012
LOGIN_DENIEDORA-01017
NO_DATA_FOUNDORA-01403
TOO_MANY_ROWSORA-01422
ZERO_DIVIDEORA-01476
INVALID_NUMBERORA-01722
STORAGE_ERRORORA-06500
PROGRAM_ERRORORA-06501
VALUE_ERRORORA-06502
CURSOR_ALREADY_OPENORA-06511

Syntax

We will take a look at the syntax for Named System Exceptions in both procedures and functions.

Syntax for Procedures

The syntax for the Named System Exception in a procedure is:

CREATE [OR REPLACE] PROCEDURE procedure_name
   [ (parameter [,parameter]) ]
IS
   [declaration_section]

BEGIN
   executable_section

EXCEPTION
   WHEN exception_name1 THEN
      [statements]

   WHEN exception_name2 THEN
      [statements]

   WHEN exception_name_n THEN
      [statements]

   WHEN OTHERS THEN
      [statements]

END [procedure_name];

Syntax for Functions

The syntax for the Named System Exception in a function is:

CREATE [OR REPLACE] FUNCTION function_name
   [ (parameter [,parameter]) ]
   RETURN return_datatype
IS | AS
   [declaration_section]

BEGIN
   executable_section

EXCEPTION
   WHEN exception_name1 THEN
      [statements]

   WHEN exception_name2 THEN
      [statements]

   WHEN exception_name_n THEN
      [statements]

   WHEN OTHERS THEN
      [statements]

END [function_name];

Example

Here is an example of a procedure that uses a Named System Exception:

CREATE OR REPLACE PROCEDURE add_new_supplier
   (supplier_id_in IN NUMBER, supplier_name_in IN VARCHAR2)
IS

BEGIN
   INSERT INTO suppliers (supplier_id, supplier_name )
   VALUES ( supplier_id_in, supplier_name_in );

EXCEPTION
   WHEN DUP_VAL_ON_INDEX THEN
      raise_application_error (-20001,'You have tried to insert a duplicate supplier_id.');

   WHEN OTHERS THEN
      raise_application_error (-20002,'An error has occurred inserting a supplier.');

END;

In this example, we are trapping the Named System Exception called DUP_VAL_ON_INDEX. We are also using the WHEN OTHERS clause to trap all remaining exceptions.

No comments:

Post a Comment

PL/SQL - Collections

A collection is an ordered group of elements having the same data type. Each element is identified by a unique subscript that represents its...