Reputation:
Suppose we a have class named DynamicClass
:
public class DynamicClass {
public void get(String input) {
System.out.println(input);
}
}
Now, imagine the following instantiating of DynamicClass
:
DynamicClass clazz = new DynamicClass();
clazz.getName();
clazz.getOther();
Of course, the calling of getName
and getOther
methods throws MethodNotFoundException
exception. However, I'm curious, is there any way to catch the MethodNotFoundException
exception inside the DynamicClass
class, i.e. the calling of get("Name")
and get("Other")
rather than throwing the MethodNotFoundException
exception due to the calling of getName()
and getOther()
?
Upvotes: 6
Views: 1220
Reputation:
With reference to this answer, it's possible to catch all uncaught Exceptions in Java:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
// TODO
}
});
Upvotes: 0
Reputation: 2345
Nice curiosity.
I am afraid, there is no other way than using try catch in Java, but if Java was a OTF(on the fly) compiler and the exception mechanism actually use a (if-responds_to?) method which expected to be declared on the top of the hierarchal pyramid of Class inheritance for example Object in Java that would be possible to override that method on your DynamicClass.
However Java doesn't use the above mechanism to control the if responds_to? and the messages which are sent to an object(class) are tested somewhere else in compiler but not as a method that you can override.
I know a language called (Magik) that has the above mechanism which is very nice and it is an OTF compiler.
the Object class in Magik has a method with name does_not_responds_to() and whenever a message is sent to an object it is tested against the class states and behaviors and finally raise or better to say run does_not_responds_to() method in case the method name(message) is invalid.
It is a very neat solution to implement the does_not_responds_to? method in the class (DynamicClass) to handle the exception before it raises. however after 10 years of experiance with Magik, never needed to do so.
Sorry, My English is not good, I hope I could explain the issue.
Upvotes: 1
Reputation: 2942
Why not?
try{
clazz.getName();
clazz.getOther();
}catch(MethodNotFoundException e){
clazz.get("Name")
}
But actually do not think that it is good idea...
Upvotes: 0