调用抛出异常的方法的Lambda返回方法

问题描述 投票:1回答:1

我有以下问题。我在method 1内工作,这个method 1应该返回某个类的对象。对于我的return语句,我调用另一个method 2(当然返回所述类的对象)。虽然这个其他method 2抛出一个例外。我应该如何在我最初的method 1中写回报表?

像这样?

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

但我想如果我这样做它只会返回null?我应该在最后一个括号后面放回null吗?或者我应该以完全不同的方式写这个?

java exception methods return throw
1个回答
4
投票

编辑。你写了

基本上通常不应该抛出异常

这是RuntimeException的完美用例。它基本上是一个透明的例外。你的代码的用户不会看到它,但是当一些特殊的事情发生时,它会像野生的口袋妖怪一样出现,并且会让你的应用程序停下来,让你有机会修复它。

您的标准代码流不会受到影响,您将避免返回null值。


Lambda表达式不允许抛出已检查的Exceptions。 CloneNotSupportedException延伸Exception

enter image description here

现在,您有两种选择

  • 像你一样处理Exception就地
  • 通过将它包裹在Exception中传播RuntimeException

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

这取决于用例,但我认为CloneNotSupportedException标志着一个错误,开发人员应该对此很明显。所以让它浮出水面。

自定义Exception只需要扩展RuntimeException,并且可能提供额外的字段来存储相关数据。

YourCustomRuntimeException extends RuntimeException { ... }

不要扔基础RuntimeException,使用自定义的。

© www.soinside.com 2019 - 2024. All rights reserved.