Skip to content

Instantly share code, notes, and snippets.

@grignaak
Created July 14, 2011 21:04
Show Gist options
  • Save grignaak/1083436 to your computer and use it in GitHub Desktop.
Save grignaak/1083436 to your computer and use it in GitHub Desktop.
Exception Utilities; including undeclared checked exceptions
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
public class Exceptions {
private static Throwable toThrow;
private Exceptions() throws Throwable {
throw toThrow;
}
public static synchronized RuntimeException rethrowAsIs(Throwable exception) {
try {
Exceptions.toThrow = exception;
Exceptions.class.newInstance();
return null;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} finally {
toThrow = null;
}
}
public static synchronized RuntimeException rethrow(Throwable exception) {
return rethrowAsIs(getExceptionToRethrow(exception));
}
private static Throwable getExceptionToRethrow(Throwable exception) {
Throwable cause = exception.getCause();
if (cause == null)
return exception;
if (exception instanceof InvocationTargetException)
return cause;
return exception;
}
public static <T extends Throwable> void declare(Class<T> toDeclare) throws T {}
public static <T extends Throwable, T2 extends Throwable>
void declare(Class<T> toDeclare, Class<T2> toDeclare2) throws T, T2 {}
public static void rethrowInterruptedException(Throwable exception) {
rethrowCauseIfPossible(exception, InterruptedException.class);
}
public static void handleInterruptedExceptionWithoutThrowing(Throwable exception) {
if (!isCausedBy(InterruptedException.class, causes(exception)))
return;
Thread.currentThread().interrupt();
}
@SuppressWarnings({ "serial", "unchecked" })
public static void rethrowCauseIfPossible(Throwable exception, Class<? extends Throwable> causeType) {
rethrowCauseIfPossible(exception, causeType, new Exception() {}.getClass());
}
public static void rethrowCauseIfPossible(Throwable exception, Class<? extends Throwable>... causeTypes) {
for (Throwable cause : causes(exception)) {
for (Class<? extends Throwable> causeType: causeTypes) {
if (causeType.isInstance(cause))
rethrowAsIs(cause);
}
}
}
public static boolean isCausedBy(Throwable exception, Class<? extends Throwable> cause) {
return isCausedBy(cause, causes(exception));
}
private static boolean isCausedBy(Class<? extends Throwable> search, List<Throwable> causes) {
for (Throwable cause : causes) {
if (search.isInstance(cause))
return true;
}
return false;
}
public static List<Throwable> causes(Throwable exception) {
List<Throwable> causes = new ArrayList<Throwable>();
for (Throwable current = exception; current != null; current = current.getCause()) {
causes.add(current);
}
return causes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment