A static block cannot throw checked exceptions but I have seen a couple of codes where checked exceptions are converted unchecked and thrown from static blocks. An example of such would be reading a text file of dictionary. We do not want to read only half the dictionary, and makes sense to throw an exception instead of catching it. But my question is - is it just a hack or a commonly followed industry wide coding style ?
Asked
Active
Viewed 53 times
1
-
1Does this help:- http://stackoverflow.com/questions/2070293/exception-in-static-initialization-block/2070409#2070409 ? – Rahul Tripathi Oct 20 '13 at 20:06
3 Answers
2
The decision to throw an unchecked exception is not a hack, it is the only choice that you have: exceptions in a static block indicate a failure of a class to initialize - something the users of the class cannot possibly handle, because it is an implementation detail of your class. In other words, any exception in a static block indicates an error in the way the programmer used your class in his or her system, so it should be either handled internally by the block, or be thrown as an unchecked exception to stop the system altogether.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
1
If you can't handle it, then you need to throw it. So it's used when it's necessary.

Kayaman
- 72,141
- 5
- 83
- 121
1
you mean like this :
static{
try{
//do something that throws a checked exception
...
}catch(Exception e){
//this is an unchecked exception
throw new IllegalStateException("error initializing", e);
}
}

dkatzel
- 31,188
- 3
- 63
- 67
-
-
There is no other way if what ever you are initializing throws a checked Exception – dkatzel Oct 20 '13 at 20:13