2
boolean pingOK = false;
try {
  pingOK = InetAddress.getByName(ip).isReachable(200);
} catch(IOException e) {
  pingOK = false;
}

Can these code cut down from 6 lines to 1 line?

Such as:

boolean pingOK = withNoException(InetAddress.getByName(ip).isReachable(200));

Maybe above Java 8 some functional exception trick?

Or under Java 7 is there some way to do this?

rufushuang
  • 302
  • 4
  • 17
  • Take a look at https://stackoverflow.com/questions/28659462/how-to-ignore-exceptions-in-java – jspcal Jul 13 '18 at 01:59

1 Answers1

6

You can make your own helper to do that:

static <T> T withNoException(Supplier<? extends T> supplier, T defaultValue) {
    try {
        return supplier.get();
    } catch (Exception e) {
        return defaultValue;
    }
}

...

boolean pingOK = withNoException(() -> InetAddress.getByName(ip).isReachable(200), false);
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • This is neat code, but please OP look at the question that jspcal linked to, esspecially these parts: "You should **never** ignore exceptions." and "I would gravely doubt the sanity of any testing code" Just because you can, doesn't mean you should. https://stackoverflow.com/questions/28659462/how-to-ignore-exceptions-in-java – markspace Jul 13 '18 at 02:12