Is it standard / recommended practice to covert checked to unchecked exceptions in static blocks?

StackOverflow https://stackoverflow.com/questions/19482202

Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

If you can't handle it, then you need to throw it. So it's used when it's necessary.

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top