I am writing a method that basically does one simple thing, log the error message and throw a runtime exception using the same error message. I want it to be able to throw any child exception of RuntimeException. The method I have got is:
public static <T extends RuntimeException> void logErrorAndThrowException(Logger logger, String errorMessage, Class<T> exceptionClazz) throws T {
logger.error(errorMessage);
RuntimeException runtimeException = new RuntimeException(errorMessage);
throw exceptionClazz.cast(runtimeException); // Not work!!
}
I have have this exception defined:
public final class MyException extends RuntimeException {
public MyException() {
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
}
I then invoke the method using:
logErrorAndThrowException(logger, "This is an error message", MyException.class);
The commented line above will fail with an cast exception. I then tried another implementation of:
public static <T extends RuntimeException> void logWarningAndThrowException(Logger logger, String errorMessage, Class<T> exceptionClazz) throws T {
logger.error(errorMessage);
try {
throw exceptionClazz.newInstance();
} catch (InstantiationException e) {
// handle
} catch (IllegalAccessException e) {
// handle
}
}
With this implementation, I can only invoke the no-arg constructor of my exception hence cannot set the error message.
Can anyone help with this?
E
then you can make it throwE1
,E2
etc which are subclasses ofE
. Unfortunately, exceptions and generics don't mix too well...throw new RuntimeException(myException)
. This avoids the above problems and keeps the stack trace of the original exception (not just the message), which often helps with debugging.