Skip to content

Instantly share code, notes, and snippets.

@zleonov
Created March 19, 2020 20:01
Show Gist options
  • Save zleonov/978bf01f64051886fdd3796d7a34f3a8 to your computer and use it in GitHub Desktop.
Save zleonov/978bf01f64051886fdd3796d7a34f3a8 to your computer and use it in GitHub Desktop.
// 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);
}
}
@zleonov
Copy link
Author

zleonov commented Mar 19, 2020

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);
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment