RuntimeException propagation from method called reflection

I start with the code. This method calls the reflection method.

try {
    Method method = states.getClass().getDeclaredMethod(
            getCurrentStateId() + "_" + request.getEvent());
    states.setData(request, dataManager);
    method.invoke(states);
} catch (NoSuchMethodException e) {
    logger.debug("Method " + getCurrentStateId() + "_" + request.getEvent()
            + " cannot be found - invocation not performed.", e);
} catch (IllegalArgumentException e) {
    throw new InternalException("Method invocation with reflection failed.", e);
} catch (IllegalAccessException e) {
    throw new InternalException("Method invocation with reflection failed.", e);
} catch (InvocationTargetException e) {
    throw new InternalException("Method invocation with reflection failed.", e);
}

and calls the method with the following code that generates PropertiesDontMatchException(runtime).

...
if (totalCredits < minimumCredits || totalCredits > maximumCredits) {
    throw new PropertiesDontMatchException("Minimum amount of credits=" + minimumCredits
            + ", maximum amount of credits=" + maximumCredits + ". Your amount of credits="                 + totalCredits + ". You have to modify your set of subjects.");
}
...

The fact is that my runtime exception is wrapped in InvocationTargetExceptionand caught in the first piece of code. This is not what I want. But according to the documentation, this is the correct behavior.

So I came up with this solution

...
} catch (InvocationTargetException e) {
    if (e.getCause() instanceof PropertiesDontMatchException) {
        throw (PropertiesDontMatchException) e.getCause();
    }
    throw new InternalException("Method invocation with reflection failed.", e);
}
...

Is this the correct way to throw my exception at runtime, or is there a better solution to this problem?

+3
source share
1 answer

, . RuntimeException:

} catch (InvocationTargetException e) {
    if (e.getCause() instanceof RuntimeException) {
        throw (RuntimeException) e.getCause();
    }
    if (e.getCause() instanceof Error) {
        throw (Error) e.getCause();
    }
    throw new InternalException("Method invocation with reflection failed.", e);
}

Throwables , RuntimeException InternalException :

} catch (InvocationTargetException e) {
    throw Throwables.propagate(e.getCause());
}

, , . IllegalAccessException .

API Future.get() - , ExecutionException .

+4

All Articles