3

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.

Community
  • 1
  • 1
sixtyfootersdude
  • 25,859
  • 43
  • 145
  • 213
  • 7
    It's a couple of lines and in almost all cases, a terrible idea. So I don't think there's a JDK-built-in exception swallower. Various testing harnesses often provide something, though. – pvg Mar 09 '17 at 00:10
  • 1
    @pvg The interface is useful, but I agree that the method is unlikely to be included in any library other than one made for unit testing. – shmosel Mar 09 '17 at 00:13
  • 2
    Yeah and even in those cases, the utilities that help you skip the exception handling will generally log them in some way. Non-local exits have implications about your code coverage, for instance, if you're into that sort of thing. – pvg Mar 09 '17 at 00:17
  • 1
    JUnit and TestNG have ways to expect exceptions, but that's a little different in that the test fails if you don't get the exception. – Lew Bloch Mar 09 '17 at 01:03

1 Answers1

6

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...
Holger
  • 285,553
  • 42
  • 434
  • 765