Java was the first (and last) language to experiment with checked exceptions. The fact that no other language has adopted this "feature" should be strong enough evidence that it was a mistake.
The "no checked exceptions" philosophy means to stop the propagation of this mistake as we move forward.
Java provides two mechanisms for unchecked exceptions. The widely-known RuntimeException
and the lesser-known Error
. The implementation of this philosophy is to simply wrap all checked exceptions in one of these two unchecked exceptions and all new exceptions that are created are of this type or a derivative.
We have created utility methods to facilitate this.
If you have a single line that throws a checked exception, you can easily wrap it in a lambda and get the same thing that you would with an unchecked exception.
If you want to rethrow from a try/catch block this method will rethrow what is passed-in wrapped in an unchecked exception (if needed). This method also states that it returns an unchecked exception allowing you to pretend to throw it, so you can easily compile code without having to add unnecessary return statements. For example:
try
{
return methodThatThrowsCheckedException();
}
catch (Exception e)
{
ObjectUtils.throwAsError(e); // Does not compile. Missing "return" statement
}
Even though this would run, it won't compile. So instead you have to write the code like:
try
{
return methodThatThrowsCheckedException();
}
catch (Exception e)
{
ObjectUtils.throwAsError(e);
return null; // This is never reached because the line above always throws an exception
}
Since this return statement is never reached, instead we write it as throwing an exception returned from the method call.
try
{
return methodThatThrowsCheckedException();
}
catch (Exception e)
{
throw ObjectUtils.throwAsError(e);
}