简体   繁体   中英

Lambda return method which calls method that throws exception

I have following issue. I'm working within a method 1 and this method 1 should return an object of a certain class. For my return statement I call another method 2 (which of course returns an object of said class). Though this other method 2 throws an exception. How should I write my return statement in my initial method 1 ?

Like this?

public class testClass {

    public testClass() {
    }

    public <T> T method1(parameter1, ...) {

     if(parameter1) {
      return () -> {
       try {
        method2(parameter1, parameter2...);
       } 
       catch (CloneNotSupportedException ex) {
        System.err.print("Error while cloning programmer");
       }
      };
    } else {
    return null;
    }
}

But I guess if I do this it will only return null? Should i put the return null after the last bracket? Or should i write this in a totally different way?

Edit. You wrote

Basically normally the exception should never be thrown

That's a perfect usecase for a RuntimeException . It's basically a transparent exception. Users of your code won't see it, but it will appear like a wild Pokemon when something extraordinary happens, and will make your application come to a stop, giving you a chance to fix it.

Your standard code flow won't be affected, and you'll avoid returning a null value.


Lambda expressions aren't allowed to throw checked Exception s.
CloneNotSupportedException extends Exception .

在此处输入图片说明

Now, you have two options

  • Handle the Exception in-place, as you did
  • Propagate the Exception by wrapping it in a RuntimeException

return () -> {
    try {
       method2(parameter1, parameter2...);
    } catch (final CloneNotSupportedException e) {
       throw YourCustomRuntimeException("Error while cloning", e /* Original cause */);
    }
};

This depends on the usecase, but I think CloneNotSupportedException signals a bug , which should be evident to you, developer. So let it surface.

The custom Exception just need to extend RuntimeException , and, maybe, provide additional fields to store relevant data.

YourCustomRuntimeException extends RuntimeException { ... }

Do not throw the base RuntimeException , use custom ones.

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