0

While doing experiment over tinylog the issue i am facing is am not able to print the run time exception logs.

For ex. int a =0 ;int b = 10;int c = b/a;

As this will give arithmetic exception but this is not getting recorder in logs.

1 Answers1

1

You just need to catch the runtime exception and pass it to the logger:

import org.tinylog.Logger;

public class Application {
    public static void main(String[] args) {
        try {
            int a = 0, b = 10;
            System.out.println(b / a);
        } catch (RuntimeException ex) {
            Logger.error(ex);
        }
    }
}

Edit: Alternatively, you can also use an UncaughtExceptionHandler for logging uncaught exceptions:

import java.lang.Thread.UncaughtHandler;
import org.tinylog.Logger;

public class Application {
    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler(new TinylogHandler());
        int a = 0, b = 0;
        System.out.println(a / b);
    }

    private static class TinylogHandler implements UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Logger.error(ex);
        }
    }
}
Martin
  • 598
  • 1
  • 4
  • 27
  • Will it be possible without try catch. As i want to see if any of my code fails and i have not written that inside try catch. – Akash Kansal Sep 26 '21 at 04:38
  • Instead you could use an [UncaughtExceptionHandler](https://medium.com/@yosimizrachi/c72e013da092) for logging uncaught exceptions. – Martin Sep 27 '21 at 07:31