简体   繁体   中英

Alternative to try-catch in a loop

I have a list of Method objects that I want to execute using user supplied parameters which I don't know the type or value until runtime.

I want to loop through the methods array and execute them using the invoke method until one of the methods executes successfully without an exception. Is this a good way to do it?

        Method[] methods = cls.getMethods();

        for (Method method : methods) {
            try {
                method.invoke(obj, param1, param2);
                break;
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

I've been told that using try and catch for flow control is bad idea, but I'm not sure why. I'm also not sure what the alternative would be in a situation like this where I expect an exception to occur in the normal execution because the user supplies the parameters.

Any help is greatly appreciated.

In this particular case , why don't you try getParametersType() . And when it parameter types matches the type of the param1 and param2 you can actually execute method.invoke(obj, param1, param2);

In general it is bad idea because you don't know how heavy a function is . So it might consume lot of processing time or cpu cycle before ultimately throwing exception.

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