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:
- Does Java8 ship with something like this that I can use out of the box?
- What utility libraries have something like this?
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.