Created
July 8, 2021 09:38
-
-
Save mattiasflodin/103c2911bf71b8e09fb37e4e2effe838 to your computer and use it in GitHub Desktop.
Utility to wrap checked exceptions into unchecked exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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