Search code examples
javatry-catchstatic-initializationarithmeticexception

try-multicatch with ExceptionInInitializerError and ArithmeticException confusion


public class HelloWorld {
   static {
    try {
        int i=10/0;
     } catch(ExceptionInInitializerError | ArithmeticException e ) {
            e.printStackTrace();
     }
   } 

   public static void main(String []args) {
        System.out.println("Hello World");
     }
}

Output:

java.lang.ArithmeticException: / by zero                                                                                                                                                                                                         
        at HelloWorld.<clinit>(HelloWorld.java:7)

There is no actual purpose to this code. But just wondered why it threw ArithmeticException over ExceptionInInitializerError. Just trying out multi-catch statement and ran into this.

The code below throws ExceptionInInitializerError. So logically, if I use try-multicatch, it should catch ExceptionInInitializerError, but its not the case here. Can anyone help me out here.

public class HelloWorld {

     static int i = 10/0;

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

Output:

Exception in thread "main" java.lang.ExceptionInInitializerError                                                                                                   
Caused by: java.lang.ArithmeticException: / by zero                                                                                                                
        at HelloWorld.<clinit>(HelloWorld.java:4) 

Solution

  • static
    {
        try
        {
            int i = 10 / 0;
        }
        catch (ExceptionInInitializerError | ArithmeticException e)
        {
            e.printStackTrace();
        }
    }
    

    This causes an ArithmeticException but since you catch it, there is not problem with the Initialization.

    static
    {
        int i = 10 / 0;
    }
    

    This causes an ArithmeticException but since you do not catch it, the ArithmeticException causes an ExceptionInInitializerError. You can see it from the stack shown below.

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.ArithmeticException: / by zero
        at src.Test.<clinit>(Test.java:23)