有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

我在用

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

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

但是它不知道是否有失败,如果堆栈跟踪中有什么东西,它就会进入if语句。有没有办法在JUnit选项卡上捕获“Errors”关键字?然后将堆栈跟踪记录到日志文件中

多谢各位


共 (1) 个答案

  1. # 1 楼答案

    您正在寻找的是一个默认的异常处理程序。(爪哇)

    下面是一个关于使用它的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");
      }
    }