简体   繁体   中英

How to catch the MethodNotFoundException exception inside the class?

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, ie the calling of get("Name") and get("Other") rather than throwing the MethodNotFoundException exception due to the calling of getName() and getOther() ?

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.

Why not?

try{
   clazz.getName();
   clazz.getOther();
}catch(MethodNotFoundException e){
   clazz.get("Name")
}

But actually do not think that it is good idea...

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
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM