0

I was going through some exercises and got really confused about handling exceptions in static initializers.

The online consensus seemed to be: Initializers can only throw unchecked exceptions, or checked exceptions when the exception is also declared by all other constructors.

However I don't understand why:

  1. Why can't initializers just throw a checked exceptions? Why does it have to be declared by other constructors? What would happen, like steps by steps, if we don't declare the exceptions?

One answer says that "because it's impossible to handle these exceptions in your source". Why is that the case? Can't people just catch the exception and handle it meaningfully? Why doesn't Java allow to throw a checked exception from static initialization block?

Another response says that if we don't declare the exception for constructors, there will be a "parameterless constructor which doesn't declare that it throws anything". I really don't understand the part for a "parameterless constructor". When an initializer simply throws a checked exception, why would that leave us with a parameterless constructor? Can initializer block throw exception?

  1. the first version of code would work but the second wouldn't.

    1.        
    static {
    try {
        if(B <= 0 || H <= 0) {
            throw new Exception("Breadth and height must be positive");    
        }
    } catch(Exception e) {
        System.out.println(e);
    }
    
    
    2.
    static {
    if(B <=0 || H<= 0){
        throw new Exception("Breadth and height must be positive");
    }
    }
    

Thanks!

Community
  • 1
  • 1
whales
  • 787
  • 1
  • 12
  • 24
  • In case 2, where could you possibly catch the exception that would be thrown? Remember that exception might occur anywhere anyone writes `MyClass.something()` just out of the blue. – Louis Wasserman Jan 07 '16 at 06:26
  • thanks. So what about simply throwing a checked exception without declaring it in other constructors? What really happen internally after that? – whales Jan 07 '16 at 06:41
  • What do you mean, "without declaring it in other constructors"? The language simply won't let you throw an undeclared checked exception. – Louis Wasserman Jan 07 '16 at 06:42
  • Like the other answer mentioned, "You can't throw a checked exception from an initializer in a class with no declared constructors, as you'll effectively be provided with a parameterless constructor which doesn't declare that it throws anything." I just don't understand this quote very well. Thanks for the help though. I realize that this question is probably just making petty differences. – whales Jan 07 '16 at 06:50

0 Answers0