简体   繁体   English

当引用的方法引发异常时,如何以方法作为参数调用另一个方法?

[英]How to call another method with a method as parameter when the referenced method throws an exception?

I've seen couple of examples of this but unfortunately none where the method throws an exception. 我已经看到了几个示例,但不幸的是,没有一个方法抛出异常。

To be clear, there is one generic method I have that receives another method as reference. 需要明确的是,我有一种通用方法可以接收另一种方法作为参考。

This method throws an exception on its method's signature, when this method (returnFullName in the example) does not throw an Exception no problem for the compiler, but when it does the compiler complains " Unhandled exception" . 当此方法(示例中的returnFullName)没有引发Exception时,此方法在其方法的签名上引发异常,而编译器则抱怨“ Unhandled exception”

I still cannot figure out how to solve this, is there any idea how to handle the exceptions in these cases? 我仍然不知道如何解决这个问题,是否有任何想法在这些情况下如何处理异常?

public class MyClass{
    private  static String returnFullName(String name) throws Exception{
            return "full name " + name;
        }

        public static String calculateByName(String name) {
            try {
                myGenericMethod("John Doe", RemoteFileUtils::returnFullName);
            } catch (Exception e) {
                return "fallback name";
            }
        }

         private static <T> T myGenericMethod(final String name, final Function<String, T> call) {
            //do stuff
            return call.apply(name);
         }
    }

You have to catch the exception that may be thrown by returnFullName . 您必须捕获returnFullName可能引发的returnFullName It must be caught in the implementation of the Function you are passing to myGenericMethod : 它必须在传递给myGenericMethodFunction的实现中myGenericMethod

    public static String calculateByName(String name) {
        return myGenericMethod("John Doe", t -> {
            try {
                return returnFullName (t);
            } catch (Exception e) {
                return "fallback name";
            }
        });
    }

Wrapping the myGenericMethod("John Doe", RemoteFileUtils::returnFullName); 包装myGenericMethod("John Doe", RemoteFileUtils::returnFullName); call with a try-catch block doesn't help, since myGenericMethod is not the method that may throw the exception. 使用try-catch块进行调用无济于事,因为myGenericMethod不是可能引发异常的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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