gpt4 book ai didi

java - 将运行时错误的堆栈跟踪打印到文件中

转载 作者:行者123 更新时间:2023-12-02 12:48:19 24 4
gpt4 key购买 nike

我有 Junit 测试,有时由于运行时错误而失败 Screen of the Failure trace

我想知道是否有一种方法可以在不使用 try catch block 并将其存储到文件中的情况下捕获此 srack 跟踪。

我正在使用

        if(Thread.currentThread().getStackTrace() != null){

logger.log(LogStatus.FAIL, "Rune Time Exception");
report.endTest(logger);
report.flush();
}

但是这不知道是否有失败,如果堆栈跟踪中存在某些内容,它就会进入 if 语句。有没有办法以某种方式捕获 JUnit 选项卡上的“Errors”关键字?然后将堆栈跟踪记录到日志文件中?

谢谢

最佳答案

您正在寻找的称为默认异常处理程序。 (Java UncaughtExceptionHandler)

这是一个tutorial关于使用它。

//ExceptionHandlerExample.java
package com.air0day.machetejuggling;

public class ExceptionHandlerExample {
public static void main(String[] args) throws Exception {

Handler handler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(handler);

Thread t = new Thread(new SomeThread(), "Some Thread");
t.start();

Thread.sleep(100);

throw new RuntimeException("Thrown from Main");
}

}

class Handler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Throwable: " + e.getMessage());
System.out.println(t.toString());
}
}

class SomeThread implements Runnable {
public void run() {
throw new RuntimeException("Thrown From Thread");
}
}

关于java - 将运行时错误的堆栈跟踪打印到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44678904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com