Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for Built-in Function in Java8 to ignore Exceptions

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.

like image 849
sixtyfootersdude Avatar asked Sep 18 '25 10:09

sixtyfootersdude


1 Answers

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...
like image 84
Holger Avatar answered Sep 21 '25 00:09

Holger