Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch a NoSuchMethodException?

There are some incompatible changes in code which I depend on. So I want to catch a NoSuchMethodException to log more information about the problem

When I'm using this:

try{
     do.something();      
}catch(NoSuchMethodException e){
     System.out.println("!");
}

I get this error "Unreachable catch block for NoSuchMethodException. This exception is never thrown from the try statement body"

I've tried to catch also java.lang.RuntimeException and check if it's NoSuchMethod but it didn't work.

Reflection will cause performance delays and don't want to use it....

Any ideas?

like image 826
npocmaka Avatar asked Dec 04 '22 07:12

npocmaka


2 Answers

You was confusing with NoSuchMethodException that is thrown only when invoking method that does not exist using reflection and NoSuchMethodError that may be thrown when you call method directly while this method exists at compile time and does not exist at runtime. It usually happens when using different versions of some external library at compile and runtime.

Bottom line: catch NoSuchMethodError

like image 127
AlexR Avatar answered Dec 06 '22 11:12

AlexR


Catch NoSuchMethodError instead. However this seems like an ugly workaround and I'd recommend just getting the incompatibility resolved.

like image 32
matt b Avatar answered Dec 06 '22 09:12

matt b