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:

JavaScript

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

JavaScript

and then I use it as:

JavaScript

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:

JavaScript

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

JavaScript

which would allow you to call:

JavaScript

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