Project's Future

43 views
Skip to first unread message

Juan Moreno

unread,
Jul 29, 2014, 1:29:46 PM7/29/14
to catch-excep...@googlegroups.com
The project's page says the following:

"Java 8's lambda expressions will make catch-exception redundant."

Can you explain how Lambdas invalidate this library? I'm having a hard time seeing the connection.

Thanks.

rw...@gmx.de

unread,
Sep 19, 2014, 10:34:26 AM9/19/14
to catch-excep...@googlegroups.com
Java 8's Lambda expressions allow you to define a callback in a single line of code.

Thus, using Java 8 a single class could implement the current behaviour of CatchException. A single class does not make a library.

Here is the CatchException code for Java 8 (compiles in Java7 as well):

CatchExceptionJava8.java

package com.googlecode.catchexception.java8;

import java.util.concurrent.Callable;

/**
 * CatchException for Java 8.
 */
public class CatchExceptionJava8 {

    private static final ThreadLocal<Exception> caughtException = new ThreadLocal<Exception>();

    public static <V> V catchException(Callable<V> callable) {

        V result = null;
        try {
            result = callable.call();
            caughtException.remove();
        } catch (Exception e) {
            caughtException.set(e);
        }

        return result;
    }

    public static Exception caughtException() {
        return caughtException.get();
    }

    public static void resetCaughtException() {
        caughtException.remove();
    }
}

CatchExceptionJava8Test.java

package com.googlecode.catchexception.java8;

import static com.googlecode.catchexception.java8.CatchExceptionJava8.catchException;
import static com.googlecode.catchexception.java8.CatchExceptionJava8.caughtException;
import static org.junit.Assert.assertTrue;

import java.util.concurrent.Callable;

import org.junit.Test;

public class CatchExceptionJava8Test {

    private static class X {

        public String doSomething(boolean exp) {
            if (exp) {
                return "ok";
            } else {
                throw new IllegalArgumentException(
                        "expression must be true but was not");
            }
        }
    }

    @Test
    public void testCatchException() throws Exception {

        final X x = new X();

        // the following code block is a single line of code in Java 8
        catchException(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return x.doSomething(false);
            }
        });

        assertTrue(caughtException() instanceof IllegalArgumentException);
    }
}

Regards
Rod

Mariusz Smykuła

unread,
Oct 23, 2014, 2:39:32 AM10/23/14
to catch-excep...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages