Skip to content
Advertisement

Java does not catch exception

I am trying to implement lambda expression for constructor. My constructor can throw an IllegalArgumentException. I tried different ways. First way is just calling lambda expression:

catchThrowable(() -> new SomeClass(testVar1, null, testVar2));

It works perfectly fine, I can catch Exception and then parse it. The problem occurs when I try to use my own interface:

interface SomeClassFactory{
        SomeClass create (String testVar1, String persId, String testVar2) throws IllegalArgumentException;
}

SomeClassFactory factory = SomeClass::new;

and then I use it as:

catchThrowable((ThrowableAssert.ThrowingCallable) factory.create(testVar1, null, testVar3));

But the last line of code does not catch any exceptions, my code gives runtime exception and stops. Can you please explain why it happens and, if possible, how to fix it?

Advertisement

Answer

What happens is that factory.create(...) is executed and the result is passed to catchThrowable, so the exception is actually thrown before the catchThrowable execution.

To fix it, you can either use a lambda:

catchThrowable( () -> factory.create(testVar1, null, testVar3));

or you can define your own interface extending ThrowableAssert.ThrowingCallable:

interface SomeClassFactory extends ThrowableAssert.ThrowingCallable {

    @Override
    SomeClass call() throws IllegalArgumentException;

}

which would allow you to call:

catchThrowable(factory);

Note that the custom interface does not allow parameters on the overridden method.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement