You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Your IDE would quickly complain about an uncaught exception. The problem is that new URL throws a MalformedURLException which is a checked exception. At this point most people just revert to using a String:
In the grand scheme of things, this works just fine, with the likely risk that you'll create multiple redundant URL google = new URL(GOOGLE) instances in different parts of your code. But what if you wanted to enforce a singleton URL instance?
Even if an error occurs initializing a static field, we are not worried about circumventing Java's exception handling mechanisms with Unchecked Java because all class initialization errors will be suppressed under a java.lang.ExceptionInInitializerError.
The Stream.map method accepts a java.util.function.Function object whose apply method does not throw a checked exception. We are forced to refactor the code and rethrow the MalformedURLException as a RuntimeException in order to get it to compile:
Unchecked Java provides an explicit method to propagate Checked Exceptions as unchecked. It is explicitly designed for cases where you are sure the caller will handle all possible exceptions thrown by this method.
Warning
Another reminder to read Unchecked Java's Safety Guide before using Unchecked Java.
Suppose you are submitting tasks which perform I/O operations to an executor service.
importstaticsoftware.leonov.common.util.function.Exceptions.uncheckedException;
...
finalExecutorServicesvc = ...
...
finalFuture<?> future = svc.submit(() -> {
finalPathpath = ...
...
try (finalReaderout = Files.newBufferedReader(path)) {
...
} catch (finalIOExceptione) {
throwUnchecked.exception(e); // rethrow the exception without wrapping it in a RuntimeException
}
});
We rethrew the IOException as unchecked because we are guaranteed that it will be stored in the returned Future.