Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging Throwable in main()

Tags:

java

throwable

Catching Throwable is unadvisable for reasons outlined in different posts. However, would it make sense to have a main structured like below? If the Throwable line is removed, then errors would not be logged.

public static void main(String[] args) {
    try {
        launchMyApplication();
    } catch (SomeCheckedException e) {
        //recover if you can, log it if you can't
    } catch (Exception e) {
        //recover if you can (unlikely), log it if you can't
    } catch (Throwable e) {
        //Don't try to recover, but log it
        logger.error("Oops: {}", e);
    }
}
like image 817
assylias Avatar asked May 09 '26 08:05

assylias


1 Answers

Implementing this way will only handle throwables thrown on the main thread.

The best way to solve this issue is to use Thread.setDefaultUncaughtExceptionHandler().

like image 94
ControlAltDel Avatar answered May 11 '26 22:05

ControlAltDel