Monday 20 October 2014

Using PRAGMA EXCEPTION_INIT for user defined exception in PL/SQL

What is PRAGMA.

PRAGMA is a compiler directive. When you define exception you can set an error_number and error message to your exception.

A compiler directive is an instruction to the compiler to complete a task before formally starting to compile the program, thus they are sometimes called pre-processor directives. Among other items, during the pre-processor step the compiler is looking for compiler directives and processes them as they are encountered.

So, when the program is compiled the exception is already initialized. So during compilation plsql understands you defined exception.

 In this section we are going to write an user defined exception.

It is very simple. We are going to use one condition, if condition does not satisfy then we will raise an exception.

declare
  lessthanzero exception;
  pragma exception_init(lessthanzero,-20000);
  n number;
  begin
   n:=-4;
  if n<0 then
     raise_application_error(-20000,'Value must be greater than zero');
  end if;
 dbms_output.put_line('The value is '||n);
 exception
    when greaterthanzero then
    dbms_output.put_line(sqlerrm(-2000));
 end;
NB: If you try with n:=-4 dbms_output message will be "Value must be greater than zero"
and if value is positive i.e. n:=4 then dbms_output message will be "The value is 4".

 You can also watch the video on plsql packages in Youtube : https://www.youtube.com/watch?v=6i9VQcBQOfI

Also can subscribe to my channel : https://www.youtube.com/subhro190776

No comments: