Page 1 of 1

[HD Pg 282, Sec. 10.3.2 - throwing-exceptions-from-static-initializers]

Posted: Wed Jul 03, 2024 5:08 pm
by raphaelzintec
hello

plz enlighten me

here you says: "Therefore, if a static initializer ends up throwing an exception, there is no way for the
application to handle that exception and to recover from it. For this reason, a static initializer is
not allowed to throw any checked exception. If the compiler sees a possibility of a checked exception
getting thrown out of a static initializer, it will generate an error"

But i still can do it with this:

Code: Select all

public class Boo {

    static int i = 5;
    static{
        try{
            if(i == 5) throw new IOException();
        }
        catch(IOException e){
            System.out.println("handle static checked exception");
        }
    }

    public static void main(String[] args) {
        Boo b = new Boo();
    }
}

Re: [HD Pg 282, Sec. 10.3.2 - throwing-exceptions-from-static-initializers]

Posted: Wed Jul 03, 2024 11:22 pm
by admin
Throwing an exception means an exception is observed as thrown out from that piece of code. But in your code, the static initializer doesn't "end with an exception" i.e. no exception is thrown out from the static initializer.