It is our belief that checked exceptions were a mistake in the Java language. Fortunately, Java provides two methods for
unchecked exceptions: RuntimeException
and Error
. Checked exceptions will also show up in the signatures of methods,
creating troubles with lambdas
Approval Utilities provides the following techniques for converting checked exceptions into unchecked exceptions.
The most basic method to do this is to wrap a checked exception in a runtime exception. Here is an example of this:
try
{
methodThatMightThrowCheckedException();
methodThatMightThrowRuntimeException();
methodThatMightThrowError();
}
catch (Throwable t)
{
throw ObjectUtils.throwAsError(t);
}
There are two things to note in this implementation.
ObjectUtils.throwAsError
will not wrap Error
or RuntimeException
as they are already unchecked.
ObjectUtils.throwAsError
pretends that it will return an Error
. The reason it does this is so that the calling code
can pretend to throw it. In practice, throwAsError()
will always throw the Error
. So whether or not you specify
a throw
at the calling code is irrelevant to the execution, but can be helpful for compilation of the calling code.
If you want to run a small piece of code without the overhead of the try/catch block, you can accomplish this through the use of lambdas. Here are examples with and without return values:
ObjectUtils.throwAsError(() -> methodThatMightThrowCheckedException());
int i = ObjectUtils.throwAsError(() -> methodThatMightThrowCheckedExceptionWithReturnValue());
If the issue is in the signature of the lambda you will need to convert from a lambda whose signature allows checked
exceptions to one that doesn't. To do this you will use either Actions.unchecked()
/ Functions.unchecked()
Here's an example which allows us to wrap a lambda that throws an IOException
:
Queryable<String> paths = files.select(Functions.unchecked(
// throws IOException
s -> new File(s).getCanonicalPath()));