From the book Java 8 for the impatient by Cay Horstmann:
Didn’t you always hate it that you had to deal with checked exceptions in a Runnable? Write a method
uncheck
that catches all checked exceptions and turns them into unchecked exceptions. For example,new Thread(uncheck( () -> { System.out.println("Zzz"); Thread.sleep(1000); })).start(); // Look, no catch (InterruptedException)!
Hint: Define an interface
RunnableEx
whoserun
method may throw any exceptions. Then implementpublic static Runnable uncheck(RunnableEx runner)
Use a lambda expression inside the uncheck function.
For which I code like this:
public interface RunnableEx {
void run() throws Exception;
}
public class TestUncheck {
public static Runnable uncheck(RunnableEx r) {
return new Runnable() {
@Override
public void run() {
try {
r.run();
} catch (Exception e) {
}
}
};
}
public static void main(String[] args) {
new Thread(uncheck(
() -> {
System.out.println("Zzz");
Thread.sleep(1000);
}
)).start();
}
}
Did I do according to what was hinted? Is there a better way of doing this?
Also there is another complementary question:
Why can’t you just use
Callable<Void>
instead ofRunnableEx?