Wednesday, October 8, 2014

NoSuchMethodException vs NoSuchMethodError in Java

As we all know that there is a clear difference between Exception and Error. You can recover from an Exception but cannot from an Error. That's the basic difference. Coming to our actual problem which related to NoSuchMethod, we have NoSuchMethodException and NoSuchMethodException.
Let us see, when and why occurs what.


NoSuchMethodException:


This exception occurs when you try to access a method which is not present in the class. Consider there is a Class called Consumer. And Consumer calling a method called sellMe() of Class Buyer which is not actually presented in Buyer class. If you are calling normally invoking this, an compile time occurs, Normally in the sense without using reflection .

If you are using reflection and trying to invoke a method using reflection like below, there are chances to get NoSuchMethodException, if your Buyer class doesn't have sellMe() method. 
Class b = Class.forName("java.blog.Buyer");  
           try {  
                Method m = b.getDeclaredMethod("sellMe", params);  
           } catch (NoSuchMethodException e) {  
                e.printStackTrace();  
           }  
Since that is a Exception you can simply catch it and can proceed with your flow, where as it is not possible with NoSuchMethodError.


NoSuchMethodError:


This error occurs when there is a method missing at run time from the other class where the method actually there while you are compiling. Confused ? Let see with an example. 

Consider you have 2 classes, Consumer and Buyer. From Consumer you called a method of Buyer using it's instance. Later you removed the method from Buyer and compile the Buyer alone. So now Consumer messed up right?, which is still trying to refer the method sellMe(). Yes it is.

You just the changed/removed a method of Buyer , where the Consumer don't know about this change and still using the same. Hence the Error arises. Usually we run into this error in cases like we are using a third party library or jar that depends on another jar. Where the first jar invoking a method in second second jar which is not at all present because of incompatible versions. Keeping the compatible versions of jar's removes the error.

Post a Comment