简体   繁体   中英

print stacktrace of runtime errors to the file

I have Junit test where sometimes it fails due to runtime errors 故障跟踪屏幕

I was wondering if there is a way to capture this srack trace without using try catch block and storing it into a file.

I was using

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

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

but this does not know if there was a failure or not, it goes into the if statement if there is a something in the stack trace. Is there a way to somehow capture the the "Errors" keyword on a JUnit tab? and then log the stack trace into the log file?

Thank you

What you are looking for is called a default exception handler. (Java UncaughtExceptionHandler )

Here is a tutorial about using it.

 //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"); } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM