2 ms·
Not all checked exceptions are bad. The main problem is that the core Java libraries tend to use them too aggressively and now of course cannot be changed. You
by mike_hearn 13y ago
Not all checked exceptions are bad. The main problem is that the core Java libraries tend to use them too aggressively and now of course cannot be changed. You really have to be sure that the caller MUST handle a particular occurrence and anything else is a bug to make an exception checked. But, I do find it helps me feel more confident in my code. Everyone hates writing error handling code, but at least with checked exceptions you can see whether it's been done properly or not.
But in Java 8 for the times when I want to disable it, I just use the following code:
public interface UncheckedRun<T> {
public T run() throws Throwable;
}
public interface UncheckedRunnable {
public void run() throws Throwable;
}
public static <T> T unchecked(UncheckedRun<T> run) {
try {
return run.run();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
public static void uncheck(UncheckedRunnable run) {
try {
run.run();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
public static void ignoreAndLog(UncheckedRunnable runnable) {
try {
runnable.run();
} catch (Throwable t) {
log.error("Ignoring error", t);
}
}
Then you can write
Foo result = unchecked(() -> getAndMaybeThrow(a, b));