Oracle中如何捕获子异常详情并与父异常一同输出
解决方案
问题根源
原代码存在两个问题:一是存储过程调用时拼写错误(Process_test_exception应为proc_test_exception);二是父块捕获异常后直接抛出新的自定义异常,覆盖了子块抛出的原始异常信息,导致仅能看到父块异常。
实现方案
要同时输出子块和父块的异常信息,需在父块的异常处理逻辑中先捕获并打印子块的异常详情,再处理父块的异常输出(可选择打印或抛出)。
1. 存储过程(无需修改)
Create or replace procedure proc_test_exception Is A number; Begin A:=1/0; Exception When others then Raise_application_error(-20090, 'error in child block'); End; /
2. 修正后的匿名块(方案一:打印子块异常+抛出父块异常)
Set serveroutput on; -- 必须开启DBMS_OUTPUT输出开关 Begin proc_test_exception; -- 修正拼写错误 Exception When others then -- 打印子块抛出的异常信息 DBMS_OUTPUT.PUT_LINE('Ora-' || ABS(SQLCODE) || ' ' || SQLERRM); -- 抛出父块自定义异常 Raise_application_error(-20099,'exception captured in parent block'); End; /
执行结果:
Ora-20090 error in child block ORA-20099: exception captured in parent block ORA-06512: at line 8
3. 修正后的匿名块(方案二:完全匹配预期输出)
若仅需输出指定的两行信息,可直接打印父块异常而非抛出:
Set serveroutput on; Begin proc_test_exception; Exception When others then DBMS_OUTPUT.PUT_LINE('Ora-' || ABS(SQLCODE) || ' ' || SQLERRM); DBMS_OUTPUT.PUT_LINE('Ora-20099 exception captured in parent block'); End; /
执行结果:
Ora-20090 error in child block Ora-20099 exception captured in parent block
内容的提问来源于stack exchange,提问作者Narasimhan M
相关产品推荐
相关产品推荐

