Created
March 19, 2020 20:01
-
-
Save zleonov/978bf01f64051886fdd3796d7a34f3a8 to your computer and use it in GitHub Desktop.
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
// public API method | |
public void someMethod() throws Exception { | |
try { | |
// some work happens here, maybe not my code | |
} catch (final Throwable t) { | |
if(t instanceof Exception || t instanceof Error) | |
// if t is an Exception or a RuntimeException the method signature already declares it | |
// if t is an Error then it is not a checked exception in the first place | |
throw UnsafeUtil.unchecked(t); | |
else | |
// for the case where t happens to be a bare Throwable (e.g. new Throwable(...)) which we would never expect to happen | |
throw new InternalError("unexpected Throwable", t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now, what about the reverse?
// public API method
public void someMethodThatDoesNotThrow() {
try {
// some work happens here, maybe not my code
} catch (final Throwable t) {
if(t instanceof RuntimeException || t instanceof Error)
// if t is a RuntimeException or Error then it is not a checked exception and we can throw it
throw UnsafeUtil.unchecked(t);
else if (t instanceof Exception)
// no alternative but to wrap it
throw new RuntimeException(t);
else
// has to be a bare Throwable (e.g. new Throwable(...)) at this point, which we would never expect to happen
throw new InternalError("unexpected Throwable", t);
}
}