1

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?

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

3

Instead of ignoring the exception, add

throw new AssertionError("this should never happen");

to the catch block. That way, if you misunderstood the documentation and this IllegalAccessException exception effectively happens, or if someone modifies the code and removes the checks that make this IllegalAccessException exception impossible, you'll have a clear exception, with a stack trace indicating the precise location where the problem is, rather than a problem later, in unrelated code, or worse: a valid but incorrect result.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255