You are on page 1of 2

how to handle exceptions and using raise_application_error

user defined exception


we use these in those cases, when user predictes some error that may occur in the
block
1) 1st define the exception in declare section
2) raise the exception in execution block where user predicts some error that may
occur
3) then handle these exception in exception block
declare
v_gender varchar2(10);
message varchar2(250);
my_exception exception;
begin
SELECT gender INTO v_gender from students WHERE student_id = 3;
dbms_output.put_line('Gender is: '||v_gender);
IF v_gender = 'M' THEN
message := 'MALE';
ELSE
RAISE my_exception;
END IF;
dbms_output.put_line('Message: '||message);
exception
when my_exception then
dbms_output.put_line('My User defined exceptions!');
end;

*RAISE_APPLICATION_ERROR*
if u want to give an error message in a more meaningful & descriptive format we use
this raise_application_error
here the error_number should always be -20999 to -20000. max message length would
be 2048 bytes.
it will abort the execution if there is a raise_application_ error

UNNAMED EXCEPTION
other than PREDEFINED EXCEPTIONS, if we want to handle any exception we go for
these i.e, nothing but pragma exception_init
pragma exception_init with this we can define your own error message and error
number
PRAGMA EXCEPTION_INIT(exception_name, -error_number);
DECLARE
myex EXCEPTION;
PRAGMA EXCEPTION_INIT(myex,-20015);
n NUMBER := &n;
BEGIN
FOR i IN 1..n LOOP
dbms_output.put.line(i);
IF i=n THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
dbms_output.put.line('loop finish');
END;

Exceptions
----------
An exception occurs when the PL/SQL engine encounters an instruction which it
cannot execute due to an error that occurs at run-time.
These errors will not be captured at the time of compilation and hence these needed
to handle only at the run-time.
Predefined Exceptions - NO_DATA_FOUND , TOO_MANY_ROWS , ZERO_DIVIDE , VALUE_ERROR
User-defined Exception
can be created at a subprogram level in the declaration part. These exceptions are
visible only in that subprogram.
The exception that is defined in the package specification is public exception,
and it is visible wherever the package is accessible.
PL/SQL Raise Exception
All the predefined exceptions are raised implicitly whenever the error occurs. But
the user-defined exceptions needs to be raised explicitly.

Rather than throwing an error we use exceptions in PL/sql blocks inorder to


terminate the program gracefully and to show more functional & meaningful readable
error message

You might also like