![](/img/trans.png)
[英]method that throws exception that calls another method that throws a different exception (java)
[英]Lambda return method which calls method that throws exception
我有以下问题。 我在method 1
,此method 1
应该返回某个类的对象。 对于我的return语句,我调用了另一个method 2
(该方法当然会返回所述类的对象)。 尽管此其他method 2
引发异常。 我应该如何在初始method 1
编写return语句?
像这样?
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? 我应该在最后一个括号之后放置return null吗? 还是我应该用完全不同的方式写这个?
编辑。 你写了
基本上,通常不应抛出异常
这是RuntimeException
的完美用例。 这基本上是一个透明的例外。 您的代码用户看不到它,但是当发生异常情况时,它看起来就像是一个狂野的Pokemon,它将使您的应用程序停止运行,从而有机会对其进行修复。
您的标准代码流不会受到影响,并且您将避免返回null
值。
不允许Lambda表达式抛出经过检查的Exception
。
CloneNotSupportedException
扩展了Exception
。
现在,您有两个选择
Exception
Exception
包装在RuntimeException
传播Exception
return () -> {
try {
method2(parameter1, parameter2...);
} catch (final CloneNotSupportedException e) {
throw YourCustomRuntimeException("Error while cloning", e /* Original cause */);
}
};
这取决于用例,但是我认为CloneNotSupportedException
发出一个bug ,对于开发人员您应该是显而易见的。 所以让它浮出水面。
自定义Exception
只需要扩展RuntimeException
,并且可能提供其他字段来存储相关数据。
YourCustomRuntimeException extends RuntimeException { ... }
不要抛出基本的RuntimeException
,而要使用自定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.