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

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

문제

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 ?

도움이 되었습니까?

해결책

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.

다른 팁

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

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top