在 Java8 中的 optional 中抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42993428/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Throw exception in optional in Java8
提问by joe paulens
There is a method get(sql)
(I can not modify it). This method returns MyObjects and it has to be in try catch block because JqlParseException
is possible there. My code is:
有一种方法get(sql)
(我无法修改它)。此方法返回 MyObjects 并且它必须在 try catch 块中,因为JqlParseException
在那里是可能的。我的代码是:
String sql = something;
try{
MyObject object = get(sql);
} catch(JqlParseException e){
e.printStackTrace();
} catch(RuntimeException e){
e.printStackTrace();
}
I want to remove try catch and use Optional
class, I tried:
我想删除 try catch 和 useOptional
类,我试过:
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new);
but IDE force there try catch too. And for:
但是 IDE 也强制尝试 catch 。对于:
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(JqlParseException::new));
is an error (in IDE) The type JqlParseException does not define JqlParseException() that is applicable
. Is there any way to avoid try catch blocks and use optional?
是一个错误(在 IDE 中)The type JqlParseException does not define JqlParseException() that is applicable
。有什么办法可以避免 try catch 块并使用 optional 吗?
采纳答案by john16384
Optional
is not really intended for the purpose of dealing with exceptions, it was intended to deal with potential nulls without breaking the flow of your program. For example:
Optional
并不是真正用于处理异常,它的目的是在不中断程序流程的情况下处理潜在的空值。例如:
myOptional.map(Integer::parseInt).orElseThrow(() -> new RuntimeException("No data!");
This will automatically skip the map
step if the optional was empty and go right to the throw
step -- a nice unbroken program flow.
map
如果可选项为空,这将自动跳过该步骤并直接进入该throw
步骤——一个不错的完整程序流程。
When you write:
当你写:
myOptionalValue.orElseThrow(() -> new RuntimeException("Unavailable"));
... what you are really saying is: Return my optional value, but throw an exception if it is not available.
...您真正要说的是:返回我的可选值,但如果不可用则抛出异常。
What you seem to want is a way to create an optional (that instantly catches the exception) and will rethrow that exception when you try using the optional.
您似乎想要的是一种创建可选(立即捕获异常)并在您尝试使用可选时重新抛出该异常的方法。
回答by stevecross
That's not how Optionals work. They don't make try-catch-blocks obsolete. However, you could introduce a new wrapper-function like this:
这不是 Optionals 的工作方式。它们不会使 try-catch-blocks 过时。但是,您可以引入一个新的包装函数,如下所示:
public Optional<MyObject> getMyObject(final String jql) {
try {
return Optional.ofNullable(get(sql));
} catch (final JqlParseException e) {
return Optional.empty();
}
}
You won't have to deal with the exception anymore, but you won't know if there was an error if you get an empty Optional as well.
您将不必再处理异常,但如果您也获得空的 Optional,您将不知道是否有错误。