找到一个被捕获的异常

Find an exception that gets caught away

原问题

鉴于以下方法是库的一部分(因此无法编辑)(另外,A() 是私有的,因此无法在 m() 之外调用):

void m() {
    try {
        A();
    } catch (Exception e) {
        B();
        throw e;
    }
}

当调用m()时,A()生成一个Exception e,因此B()被执行。然而,B() 也会抛出一个异常,然后向上传递(而不是 e,后者会在一行之后向上传递)。

是否可以找到 Exception e?也许使用一些智能反射或多线程暂停和运行方法?

解释我为什么选择最佳答案,以及其他可能有帮助的内容

诚的回答:

e is lost because any exception that is thrown will cause execution to complete abruptly.

是我问题的正确答案(即无法以编程方式检索 Exception e)。

但是,我想指出肖恩帕特里克弗洛伊德的评论:

If you can't change the code, your only chance is to use a debugger and set a breakpoint inside the catch block.

和 Pinkie Swirl 的评论:

Note that through debugging one could still see e and its information (stack trace etc..)

实际上帮助我解决了我的问题:通过调试器(我得到的异常是 SQLException,所以我真的需要知道它是什么来解决我的问题)。

e 丢失,因为抛出的任何异常都会导致执行到 complete abruptly.

考虑这个(有效代码):

void m() throws Exception {
    try {
        A();
    } catch (Exception e) {
        B();
        throw e;
    }
}

private void B() {
    throw new RuntimeException("No!!!!");
}

private void A() throws Exception {
    throw new RuntimeException("Do I make it??");
}

调用 B() 的语句将导致整个方法 m() 突然完成,因为抛出了异常。这意味着当前代码块中的 nothing 可以再访问 e

从另一个角度来看,如果你要翻转 catch...

中语句的顺序
void m() throws Exception {
    try {
        A();
    } catch (Exception e) {
        throw e;
        B();
    }
}

...对 B() 的调用将被视为无法访问,因为编译器可以保证永远不会执行 B()。同样的事情也发生在这里,需要注意的是编译器 不能 确定 B() 是否绝对保证在执行期间抛出异常。

在大多数调试器下,例如Intellij 您可以在 抛出 而不是处理异常时设置断点。

您还可以过滤 class 或该抛出语句的其他条件。