1

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 ?

4

3 回答 3

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.

于 2013-10-20T20:13:25.173 回答
1

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

于 2013-10-20T20:06:55.640 回答
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);
   }

}
于 2013-10-20T20:12:18.713 回答