Skip to content

Instantly share code, notes, and snippets.

@mattiasflodin
Created July 8, 2021 09:38
Show Gist options
  • Save mattiasflodin/103c2911bf71b8e09fb37e4e2effe838 to your computer and use it in GitHub Desktop.
Save mattiasflodin/103c2911bf71b8e09fb37e4e2effe838 to your computer and use it in GitHub Desktop.
Utility to wrap checked exceptions into unchecked exceptions
import java.io.IOException;
import java.io.UncheckedIOException;
public class Exceptions {
private Exceptions()
{
}
private static class WrappedCheckedException extends RuntimeException {
public static final long serialVersionUID = 1L;
public WrappedCheckedException(Exception e) {
super(e);
}
}
public static RuntimeException wrap(Exception e) {
if (e instanceof IOException) {
return new UncheckedIOException((IOException) e);
} else {
return new WrappedCheckedException(e);
}
}
public static Exception unwrap(Exception e) {
if (e instanceof WrappedCheckedException || e instanceof UncheckedIOException) {
var cause = e.getCause();
if (cause instanceof Exception) {
return (Exception) cause;
} else {
return e;
}
} else {
return e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment