用户定义的异常不会向调用应用程序提供任何消息。它只会得到一个通用的“ORA-06510: PL/SQL: unhandled user-defined exception”。 raise_application_error 可让您传递描述实际问题的消息。
declare
out_of_stock exception;
begin
raise out_of_stock;
end;
/
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 4
begin
raise_application_error(-20000, 'Cheese is out of stock');
end;
/
ERROR at line 1:
ORA-20000: Cheese is out of stock
ORA-06512: at line 2
pragma exception_init(exception_name, error_code) 允许您将自己的用户定义异常与系统错误代码相关联。从编程的角度来看,这可能很有用,但最终它不会为调用者增加任何价值:
declare
invalid_day_of_month exception;
pragma exception_init(invalid_day_of_month, -1847);
d date;
begin
d := to_date('99-JAN-2020','DD-MON-YYYY');
exception
-- Pointless exception handler - just to demo raising a user-defined exception
when invalid_day_of_month then raise;
end;
/
ERROR at line 2:
ORA-01847: day of month must be between 1 and last day of month
ORA-06512: at line 10
ORA-06512: at line 7
通过 OUT 参数传递成功/失败状态通常是一个坏主意,因为过程看起来已经成功完成,调用者必须读取状态以查看它是否真的成功。