Home > PL/SQL > PRAGMA EXCEPTION_INIT的用法

PRAGMA EXCEPTION_INIT的用法

 如果要处理未命名的内部异常,必须使用OTHERS异常处理器或PRAGMA EXCEPTION_INIT 。PRAGMA由编译器控制,或者是对于编译器的注释。PRAGMA在编译时处理,而不是在运行时处理。EXCEPTION_INIT告诉编译器将异常名与ORACLE错误码结合起来,这样可以通过名字引用任意的内部异常,并且可以通过名字为异常编写一适当的异常处理器。
  
  在子程序中使用EXCEPTION_INIT的语法如下:
  PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number);

  在该语法中,异常名是声明的异常,下例是其用法:
  DECLARE
  deadlock_detected EXCEPTION;
  PRAGMA EXCEPTION_INIT(deadlock_detected, -60);
  BEGIN
  … — Some operation that causes an ORA-00060 error
  EXCEPTION
  WHEN deadlock_detected THEN
  – handle the error
  END;
下面看一个例子
create or replace procedure SP_Del_Test
(P_ItemAdmin in mfitem.itemadmin%type, –ItemAdmin
P_ItemCd in mfitem.itemcd%type, –ItemCode
P_Return out number –输出参数
) is
exp exception;
PRAGMA Exception_Init(exp, -2292);
begin
delete from mfitem t
where t.itemcd = P_ItemCd
and t.itemadmin = P_ItemAdmin; –这一句会引发-2292异常,有级连删除异常
EXCEPTION
WHEN EXP THEN
P_Return := 9;
ROLLBACK;
WHEN OTHERS THEN
ROLLBACK;
end SP_Del_Test;  
使用自定义的异常,自定我们自己的错误消息:过程RAISE_APPLICATION_ERROR
调用RAISE_APPLICATION_ERROR的语法如下:
raise_application_error(error_number, message[, {TRUE | FALSE}]);
error_number是一个范围在-20000至-20999之间的负整数,message是最大长度为2048字节的字符串。如果第三个可选参数为TRUE的话,错误就会被放到前面错误的栈顶。如果为FALSE(默认值),错误就会替代前面所有的错误。
CREATE PROCEDURE raise_salary (emp_id NUMBER, amount NUMBER) AS
curr_sal NUMBER;
BEGIN
SELECT sal
INTO curr_sal
FROM emp
WHERE empno = emp_id;
IF curr_sal IS NULL THEN
/* Issue user-defined error message. */
raise_application_error (-20101, ‘Salary is missing’);
ELSE
UPDATE emp
SET sal = curr_sal + amount
WHERE empno = emp_id;
END IF;
END raise_salary;
如何抛出PL/SQL异常
DECLARE
out_of_stock EXCEPTION;
number_on_hand NUMBER (4);
BEGIN

IF number_on_hand < 1 THEN
RAISE out_of_stock;
END IF;
EXCEPTION
WHEN out_of_stock THEN
– handle the error
END;
 
Categories: PL/SQL Tags:
  1. No comments yet.
  1. No trackbacks yet.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Videos, Slideshows and Podcasts by Cincopa Wordpress Plugin