Tomasz Wida
Tomasz Wida

Reputation: 359

print stacktrace of runtime errors to the file

I have Junit test where sometimes it fails due to runtime errors Screen of the Failure trace

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

Upvotes: 0

Views: 569

Answers (1)

Tezra
Tezra

Reputation: 8833

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

Upvotes: 1

Related Questions