I have an integration test where one of the methods I am calling sometimes throws an exception. I would like to ignore the exception but I would like to do it in the most elegant way possible.
Initially I was doing this like this:
// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();
// WHEN
try{
coffee.spill()
}catch(Exception e){
// Ignore this exception. I don't care what coffee.spill
// does as long as it doesn't corrupt my newspaper
}
// THEN
Assert.assertTrue(newspaper.isReadable);
While browsing stackoverflow, I noticed in this answer that I could rewrite my code like this:
// GIVEN
NewsPaper newspaper = new NewsPaper();
Coffee coffee = new Coffee();
// WHEN
ingoreExceptions(() -> coffee.spill());
// THEN
Assert.assertTrue(newspaper.isReadable);
However, I need to provide my own implementation of {{ignoringExc}}:
public static void ingoreExceptions(RunnableExc r) {
try { r.run(); } catch (Exception e) { }
}
@FunctionalInterface public interface RunnableExc { void run() throws Exception; }
Questions:
This seems like a general enough piece of code that I should be able to use someone else's. Don't want to reinvent the wheel.
The simplest way using builtin features, I can come up with is
new FutureTask<>(() -> coffee.spill()).run();
The FutureTask doesn’t ignore exceptions, but catches and records them, so it’s still your decision not to query the result.
If spill() has been declared void, it can’t be used as Callable that simple, so you would have to use
new FutureTask<>(() -> { coffee.spill(); return null; }).run();
But it’s debatable, whether any lambda expression based solution can be a simplification of your original code, which only looks less concise due to linebreaks:
try{ coffee.spill(); } catch(Exception e){}
ignoreExceptions(() -> coffee.spill());// saved four chars...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With