The problem is that it is lambda that throws an exception, and the lambda used in forEach is not declared to throw an exception. See Consumer documentation.
The best way to solve this problem is to use the old form for each cycle:
for (Method method : methods) { method.invoke(instance); }
Although you can use something like this:
methods.forEach(method -> { try { method.invoke(instance); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } });
In my opinion this really will not help, because you can no longer throw the same exception from lambda, you have to wrap it in a RuntimeException , which is not so nice ...
IntelliJ cannot fix it either. In intent actions, if I choose the Add Exceptions to Signature method, it does nothing.
The reason IntelliJ cannot do this is because it is part of the Consumer interface, which is part of the JDK. IntelliJ has no way to change this. Of course, IntelliJ could handle this better.
Conclusion:
There are times when lambdas are useful, and there are times when old ways to do things better.
source share