Benji's Blog

Try as Expression in Java 8

I’ve been familiarising myself with the new Java 8 language features. It’s great how much easier it is to work around language limitations now that we have lambdas.

One annoyance with Java is that try blocks cannot be used as expressions.

We can do it with “if” conditionals using the ternary operator.

    String result = condition ? "this" : "that";

But you cannot do the equivalent with a try block.

However, it’s fairly easy now that we have lambdas.

    @Test public void should_return_try_value() {
        String result = Try(() -> {
            return "try";
        }).Catch(NullPointerException.class, e -> {
            return "catch";
        }).apply();

        assertEquals("try", result);
    }

Code and more tests on github