Home > OS >  Can I avoid illgealAccessException when checking if Class private fields are null or empty?
Can I avoid illgealAccessException when checking if Class private fields are null or empty?

Time:02-23

This is the block of code inside the boolean method that I want to check if there are any empty or null fields. It returns true if none of them are. If they are, it throws a custom exception for each case, but it messes up my entire program when it makes me throw the IllegalAccessException.

for(Field f: getClass().getDeclaredFields()) {
    f.setAccessible(true);
    try {
        if((f.get(this)) == null) {
            throw new NullValueException("Error, this book has null value");
        }
        if(f.get(this).toString().isEmpty()) {
            throw new ItemEmptyException("Error, this book has null value");
        }
    }catch (IllegalAccessException e) {
        throw e;
    }
}

Even if I use f.setAccessible(true), it still makes me use try-catch clause for the exception. Can I avoid that try-catch clause and never have to throw an IllegalAccessException?

CodePudding user response:

The compiler looks at the declaration of the methods you use. If a method is declared to (possibly) throw a checked exception, the caller must either handle that exception or declare to throw it as well, delegating exception handling to their caller. In your example you call f.setAccessible(true); so you probably won't encounter a IllegalAccessException, but the compiler does not know this.

In your code, I'd add a comment to the catch block stating why this should never happen (you set the fields to accessible).

If you don't want to burden your callers with dealing with IllegalAccessExceptions, throw something else instead. If it's really virtually impossible that your code triggers a IllegalAccessException, you could throw an unchecked exception like IllegalStateException, or use an assert to indicate that something went really unexpectedly wrong.

  • Related