I'm reading J. Bloch's Effective Java and now I'm at the section about checked/unchecked exceptions. He said that (emphasize mine):
By confronting the API user with a checked exception, the API designer pre- sents a mandate to recover from the condition. The user can disregard the mandate by catching the exception and ignoring it, but this is usually a bad idea(Item 65).
Now, consider a method returning a list of all static data members of a class having the same type or a subtype:
public static <T> List<? extends T> getPublicStaticFields(Class<T> clazz){
List<T> fields = new ArrayList<>();
for(Field f : clazz.getDeclaredFields()){
if(Modifier.isStatic(f.getModifiers()) &&
Modifier.isPublic(f.getModifiers())){
Object fieldValue;
try {
fieldValue = f.get(null);
if(clazz.isAssignableFrom(fieldValue.getClass()))
fields.add((T) fieldValue);
} catch (IllegalAccessException e) { } // <------- Ignoring the execption
}
}
return Collections.unmodifiableList(fields);
}
The thing is I have no idea what I should put in the exception handler. I perform the access checking in the if condition:
f(Modifier.isStatic(f.getModifiers()) &&
Modifier.isPublic(f.getModifiers()))
therefore IllegalAccessViolation
will never be thrown. Moreover it seems a little confused why IllegalAccessViolation
is checked. I think it's a programming error, and judjing by what he said:
use checked exceptions for conditions from which the caller can reasonably be expected to recover
[...]
Use runtime exceptions to indicate programming errors
I though it should be an uncheked one.
QUESTION: Is it considered appropriate to leave a hadler of a checked exception empty if we ensured that the expcetion will never be thrown somewhere before?