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:
- 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?
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!