0

I noticed an issue that an exception in my static block was not captured by a try-catch in the main() method. Do I miss anything? Below is my code:

public class MyService {
     ......
     public static void main(String[] args) throws Exception {
        try {
            MyService.getInstance().run(args);
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
}


public class MyBo {
      static {
            aMethod();
      }

      ......

      private static void aMethod() {
            ......
            throw new RuntimeException("blar");
      }
}

When I run above code and the throw step got hit, the application will exit with -1 but the error is not captured and no stack trace printed out.

I know I can add a try catch at the static block and print it, but just don't know why the try catch at very high level (in the main class) didn't capture it. Can anyone explain it? Thanks in advance.

Laodao
  • 1,547
  • 3
  • 17
  • 39
  • 3
    The static block is executed (and the exception is thrown) when the class is *loaded*, not when you call `MyService.getInstance().run(args);`. In this particular case, the class is loaded before even hitting the `main` method. – Kayaman Jul 31 '20 at 05:58
  • See also https://stackoverflow.com/questions/8550567/what-does-when-a-class-is-loaded-actually-mean – Kayaman Jul 31 '20 at 06:22
  • It would help if you could provide a [mcve] - there's no `getInstance` method shown, nor `run`, nor any reference from `MyService` to `MyBo`. – Jon Skeet Jul 31 '20 at 06:55

1 Answers1

0

You will get the following exception:

java.lang.ExceptionInInitializerError

And if you follow ex.printStackTrace(), you should also see that's caused by:

java.lang.RuntimeException
Hulk
  • 6,399
  • 1
  • 30
  • 52
Soni
  • 142
  • 8
  • Thanks for your replying. Soni. However, The ExceptionInInitalizerError has already been handled caused the "Throwable" is put in the catch. And it won't capture the exception it runs. – Laodao Jul 31 '20 at 19:41