跟踪该点直到代码运行

Aka*_*uja 0 java

我需要跟踪这一点,直到代码运行.考虑下面给出的程序:

function f() throws Exception{
    statement 1 //can throw exception
    statement 2 //can throw exception
    statement 3 //can throw exception
}
Run Code Online (Sandbox Code Playgroud)

我需要一种机制来识别异常发生的位置,一种方法是使用异常来做到这一点,即在异常本身中创建一个变量,或者通过引用函数f传递一些东西并使用它来识别函数在什么时候执行跑得很成功.

哪种方式更好,还是有更优雅的方法呢?

Pet*_*rey 5

一个常见的错误是不打印堆栈跟踪,或者根本不打印异常.在大多数情况下不要这样做,因为你丢弃了有用的信息.

我会使用调试器逐步执行代码或找到引发异常的确切点,或者您可以读取异常的堆栈跟踪.

public static void f() throws Exception {
    statement1(); //can throw exception line 101
    statement2(); //can throw exception line 102
    statement3(); //can throw exception line 103
}
Run Code Online (Sandbox Code Playgroud)

当堆栈跟踪显示它在第101,102或103行引发异常时,这会告诉您它正在执行哪个语句.

如果你需要在运行时执行此操作,每次将每个都放在try/catch块中时执行不同的操作.

public static void f() throws Exception {
    try {
        statement1();
    } catch (TheException e) {
        doSomething1();
        // return or throw
    }
    try {
        statement2();
    } catch (TheException e) {
        doSomething2();
        // return or throw
    }
    try {
        statement3();
    } catch (TheException e) {
        doSomething3();
        // return or throw
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 读取堆栈跟踪的@AkashdeepSaluja也可以在运行时完成,但是您需要知道行号的含义.更好的方法是在期望不同的行为时使用不同的异常,或者将每个语句放在它自己的try/catch块中. (3认同)