The problem is that testSaveEmptyApplication
is not declared to throw any checked exceptions. But e.getCause()
returns Throwable
which is a checked exception. So what you are doing in your example code is breaking Java's checked exception rules.
If you know that the cause really is a RuntimeException
, then you can do this
throw (RuntimeException) e.getCause();
Caveats:
However, if your assumption is incorrect and the cause exception's actual class is a checked exception, the above will result in a (brand new) ClassCastException
which squashes the cause exception you were trying to rethrow.
The above will also break if the cause was an Error
, but you could deal with that; e.g something like this.
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
} else {
throw new AssertionError("Unexpected exception class", cause);
}
If you want to be able to rethrow checked exceptions, then they must be declared in the method signature. Once you have done that you can discriminate and throw them as per the above pattern.
This is all a bit cumbersome. But this is the price you pay for having wrapped the exception in the first place.