Given that I basically want to eliminate checked exception usage and transform them to runtime exceptions, I would normally be doing something like this:
try {
Project Lombok allows you to disable checked exceptions altogether.
class IORuntimeException extends RuntimeException {
final IOException ioex;
public IORuntimeException(IOException ioex) {
this.ioex = ioex;
}
@Override
public String getMessage() {
return ioex.getMessage();
}
@Override
public StackTraceElement[] getStackTrace() {
return ioex.getStackTrace();
}
//@Override
// ...
}
(Full class available here, as produced by Eclipse "Generate Delegate Methods" macro.)
Usage:
try {
...
} catch (IOException ioex) {
throw new IORuntimeException(ioex);
}
As of Java 8 there's another way:
try {
// some code that can throw both checked and runtime exception
} catch (Exception e) {
throw rethrow(e);
}
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
* More info here.
Follow up from my comment. Here's an article that has to throw some light on the issue. It uses sun.misc.Unsafe
to rethrow exceptions without wrapping them.
sounds like you actually NEED checked Exceptions
If you're considering the other answer's use of Unsafe (I recommend not, but anyway), another option is to abuse generics to throw a checked exception with this evil pair of methods (from http://james-iry.blogspot.co.uk/2010/08/on-removing-java-checked-exceptions-by.html):
@SuppressWarnings("unchecked")
private static <T extends Throwable, A>
A pervertException(Throwable x) throws T {
throw (T) x;
}
public static <A> A chuck(Throwable t) {
return Unchecked.
<RuntimeException, A>pervertException(t);
}
You might also check out com.google.common.base.Throwables.getRootCause(Throwable)
and just print its (root) stack trace.