jpganz18
jpganz18

Reputation: 5858

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".

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

Upvotes: 0

Views: 39

Answers (1)

Eran
Eran

Reputation: 393841

You have to catch the exception that may be thrown by returnFullName. It must be caught in the implementation of the Function you are passing to 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); call with a try-catch block doesn't help, since myGenericMethod is not the method that may throw the exception.

Upvotes: 1

Related Questions