跟踪点,直到代码运行(Tracking the point until when the code ran)

编程入门 行业动态 更新时间:2024-10-26 21:29:10
跟踪点,直到代码运行(Tracking the point until when the code ran)

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

function f() throws Exception{ statement 1 //can throw exception statement 2 //can throw exception statement 3 //can throw exception }

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

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

I need to track the point until when the code ran. Consider the program given below:

function f() throws Exception{ statement 1 //can throw exception statement 2 //can throw exception statement 3 //can throw exception }

I need a mechanism to identify at what point the exception occurred, one way is to do this using exceptions, i.e. creating a variable in exception itself, or pass something by reference to function f and use it to identify at what point did the function the ran successfully.

Which is the better way, or is there any more elegant way to do this?

最满意答案

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

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

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

当堆栈跟踪显示它在第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 } }

A common mistake is to not print out the stack trace, or not print out the exception at all. Don't do that in most cases, because you are throwing away useful information.

I would use the debugger to step through the code or find the exact point an exception is thrown, or you could read the stack trace for the exception.

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

When the stack trace says it threw an exception on line 101, 102 or 103, this tells you which statement it was executing.

If you need to do this at runtime, doing something different each time I would put each one in a try/catch block.

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 } }

更多推荐

本文发布于:2023-07-30 01:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   Tracking   point   code   ran

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!