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

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
raphaelzintec
Posts: 167
Joined: Sun Apr 21, 2024 10:43 am
Contact:

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

Post 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();
    }
}

admin
Site Admin
Posts: 10386
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 8 guests