owner

Discussions  - 
 
I noticed that the catch-exception library isn't maintained anymore because the author states that the lambda expressions of Java8 makes it redundant. However, I was unable to find a tutorial which would describe how I can implement the same functionality with lambda expressions.

Any help is appreciated!
4
Frank Appel's profile photoPetri Kainulainen's profile photoRafał Borowiec's profile photo
6 comments
 
Maybe it is meant like the following example. Consider a class Foo:

public class Foo {
  public void doit() throws IllegalStateException {
    throw new IllegalStateException("bad");
  }
}

A test that checks for the exception can use lambdas like this:

public class FooTest {
 @Test
  public void testFoo() {
    Foo foo = new Foo();

    Throwable actual = Exceptions.execute(()-> foo.doit());

    assertTrue(actual instanceof IllegalStateException );
  }
}

As you note you need a little helper class I named Exceptions (well tonight I am not very good with names - sorry it's in the soccer break) which basically encapsulates the usual try-catch approach used by plain old JUnit tests:

class Exceptions {

  interface Executor {
    void execute() throws Throwable;
  }


  public static Throwable execute(Executor executor) {
    Throwable result = null;
      try {
        executor.execute();
        fail();
      } catch (Throwable throwable) {
        result = throwable;
      }
    return result;
  }
}

Of course there is probably much to improve, but maybe that's what the author meant.
 
Frank, thank you for your comprehensive answer! I will take a closer at it tomorrow (I am waiting for the football game as well).
 
The original blog post about testing exception with Java 8 and Lambda Expressions I wrote (referred in +Frank Appel post)
 
Both of these blog posts convinced me to start learning the functional parts of Java 8 :)
 
Correct. Check out this book:
Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

by Venkat Subramaniam


Add a comment...