Skip to content

Instantly share code, notes, and snippets.

@michael-simons
Last active December 17, 2015 22:19
Show Gist options
  • Select an option

  • Save michael-simons/5681119 to your computer and use it in GitHub Desktop.

Select an option

Save michael-simons/5681119 to your computer and use it in GitHub Desktop.
This code "unchecks" checked exceptions without wrapping them in RuntimeException and polluting the stacktrace.
package ac.simons.utils;
/**
* Use it like throw Unchecker.uncheck(checkedException);
*
* @author Michael J. Simons, 2012-02-03
* http://www.gamlor.info/wordpress/2010/02/throwing-checked-excpetions-like-unchecked-exceptions-in-java/
*/
public final class Unchecker {
private Unchecker(){}
// Now this returns an exception, so that you can satisfy the compiler by throwing it.
// But in reality we throw the given exception!
public static RuntimeException uncheck(final Exception ex){
// Now we use the 'generic' method. Normally the type T is inferred
// from the parameters. However you can specify the type also explicit!
// Now we du just that! We use the RuntimeException as type!
// That means the throwsUnchecked throws an unchecked exception!
// Since the types are erased, no type-information is there to prevent this!
Unchecker.<RuntimeException>throwsUnchecked(ex);
// This is here is only to satisfy the compiler. It's actually unreachable code!
throw new AssertionError("This code should be unreachable. Something went terrible wrong here!");
}
/**
* Remember, Generics are erased in Java. So this basically throws an Exception. The real
* Type of T is lost during the compilation
*/
@SuppressWarnings("unchecked")
private static <T extends Exception> void throwsUnchecked(Exception toThrow) throws T{
// Since the type is erased, this cast actually does nothing!!!
// we can throw any exception
throw (T) toThrow;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment