You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:14:57