0

I want to write a json file recording the execution duration and unhandled exception if any once.

Java provides Runtime.addShutdownHook and Thread.setDefaultUncaughtExceptionHandler

However, Runtime.addShutdownHook is called regardless of whether the app is shutting down due to unhandled exception or normal completion.

What is a good way to log the unhandled exception only when it happens. I have a few different cmd line apps that require similar logging so i am avoiding using try-catch-finally construct.

user21479
  • 1,179
  • 2
  • 13
  • 21
  • 1
    `setDefaultUncaughtExceptionHandler` would do it. Why are you even looking at `addShutdownHook` for logging exceptions? – Andreas Jun 14 '19 at 23:45
  • if there is no exception, i still want to log the execution duration. setDefaultUncaughtExceptionHandler would only fire when there is an exception – user21479 Jun 15 '19 at 00:00
  • *"However, Runtime.addShutdownHook is called regardless of whether the app is shutting down due to unhandled exception or normal completion"* Yes, because it is called when the *process* ends. The setDefaultUncaughtExceptionHandler call called for each *thread* that ends with an uncaught exception. If you program is single-threaded and you only want log of execution time for successful completion, or log for exception, but not both, the `try-catch` in `main` would be the way to go. – Andreas Jun 15 '19 at 01:09
  • is there any execution ordering between shutdown and unhandled exception hooks? i am guessing thread would terminate first and then runtime but it would be nice to fins it in some documentation. if such ordering is guaranteed, i could remember unhandled exception and write it and execution time in shutdown hook – user21479 Jun 16 '19 at 00:25

0 Answers0