Reputation: 177
I'm confused by checked exception of java
Checked Exception requires to be handled at compile time using try, catch and finally keywords or else compiler will flag error
My problem is: we all know "NoSuchMethodExcepion" is checked exception, and take the statement above into consideration, does it means that whenever I try to call a method, I should use try,catch to include the method calling code like this
try{
callingMethod();
}
catch(Exception){
}
But in fact, I don't need to do that right? Then what's the really meaning of the statement that given in the first place? Thanks you for answering my question.
Upvotes: 5
Views: 366
Reputation: 60957
NoSuchMethodException
is a subtype of ReflectiveOperationException
, so it can only be thrown by code that uses reflection. For normal method calls like your example, it is a compile-time error for the method to not exist, so your code won't compile at all.
If you compile your class with one version of a dependency and then run it with a different version, it is possible for a method that existed at compile time to disappear. In this case you'll get a NoSuchMethodError
(which is an Error
, not an Exception
) when the code is executed instead.
Upvotes: 10
Reputation: 159114
NoSuchMethodException
is not the same as NoSuchMethodError
.
NoSuchMethodException
is thrown by calls to reflection API methods such as getMethod()
and getConstructor()
. See the "Uses" page of the javadoc for more.
NoSuchMethodError
is thrown.... well, quoting javadoc:
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
Upvotes: 1
Reputation: 34557
NoSuchMethodException is a checked exception which can only be thrown when you invoke methods which explicitly throw it. These are the methods in reflection package such as Class.getMethod() etc. You are mistaken when you think that any method invocation can throw this exception.
See also: http://docs.oracle.com/javase/7/docs/api/java/lang/class-use/NoSuchMethodException.html
Upvotes: 2