简体   繁体   English

在Java8中的可选中抛出异常

[英]Throw exception in optional in Java8

There is a method get(sql) (I can not modify it).有一个方法get(sql) (我不能修改它)。 This method returns MyObjects and it has to be in try catch block because JqlParseException is possible there.此方法返回 MyObjects 并且它必须在 try catch 块中,因为那里可能出现JqlParseException My code is:我的代码是:

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 并使用Optional类,我试过:

MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new);

but IDE force there try catch too.但 IDE 也强制在那里尝试捕捉。 And for:对于:

MyObject object = Optional.ofNullable(get(sql)).orElseThrow(JqlParseException::new));

is an error (in IDE) The type JqlParseException does not define JqlParseException() that is applicable .是错误(在 IDE 中) The type JqlParseException does not define JqlParseException() that is applicable Is there any way to avoid try catch blocks and use optional?有什么办法可以避免 try catch 块并使用 optional 吗?

Optional is not intended for the purpose of dealing with exceptions, it was intended to deal with potential null s without breaking the flow of your program. Optional的目的不是为了处理异常,而是为了在不破坏程序流程的情况下处理潜在的null For example:例如:

 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.您似乎想要的是一种创建可选项(立即捕获异常)并在您尝试使用可选项时重新抛出该异常的方法。

That's not how Optionals work.这不是 Optional 的工作方式。 They don't make try-catch-blocks obsolete.他们不会让 try-catch-blocks 过时。 However, you could introduce a new wrapper-function like this:但是,您可以像这样引入一个新的包装函数:

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,您将不知道是否有错误。

Try this尝试这个

Optional.ofNullable(result)
                .orElseThrow(() -> new GenericClientException("Request body is not valid", HttpStatus.BAD_REQUEST));

if (StringUtils.isEmpty(message)) {如果(StringUtils.isEmpty(消息)){

            throw new ValidationException("empty message body received from the queue");

in java 8在 Java 8 中

Optional.ofNullable(message).filter(message -> !message.isEmpty()).orElseThrow(() -> new ValidationException("empty message body received from the queue") Optional.ofNullable(message).filter(message -> !message.isEmpty()).orElseThrow(() -> new ValidationException("从队列接收到空消息体")

        );
            

Optional helps to deal with NullPointerException. Optional 有助于处理 NullPointerException。

You can use it to cast new exceptions as mentioned.如前所述,您可以使用它来投射新的异常。

MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new);

However, your method get(sql) is not returning NULL, which invalidates the use of OPTIONAL as desired.但是,您的方法get(sql)没有返回 NULL,这会根据需要使 OPTIONAL 的使用无效。

I would keep using Try Catch.我会继续使用 Try Catch。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM