0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, I just found out but this is the correct answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.