如何在可选类

时间:2018-07-12 12:54:25

标签: java optional

如果我的对象ID是NotFoundException,我有一个抛出null的方法。

public void removeStatementBundleService(String bundleId) throws NotFoundException {
    Optional<StatementBundle> bundleOpt = statementBundleRepository.findById(bundleId);

    if(bundleOpt.isPresent()) {
        StatementBundle bundle = bundleOpt.get();

        if(bundle.getStatements() != null && !bundle.getStatements().isEmpty()) {               
            for(Statement statement: bundle.getStatements()) {
                statementRepository.delete(statement);
            }
        }

        if(bundle.getFileId() != null) {
            try {
                fileService.delete(bundle.getFileId());
            } catch (IOException e) {
                e.printStackTrace();
            }   
        }

        statementBundleRepository.delete(bundle);

    } else {
        throw new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");
    }
}

我发现这是不需要的,因为使用了java.util.Optional类。在oracle文档中,我发现如果使用get()且没有任何值,则抛出NoSuchElementException。我可以将错误消息添加到异常的最佳方法是什么。我正在尝试在Eclipse中打开Optional类以尝试在其中进行更改(不确定这是否是一种好习惯),但是另一方面,Eclipse不允许我访问该类,因为我读到该类也是最终的。

3 个答案:

答案 0 :(得分:3)

解析Optional value时,如果值不存在,您可以直接抛出异常

Optional<StatementBundle> bundleOpt = statementBundleRepository.findById(bundleId);
StatementBundle bundle = bundleOpt.orElseThrow(() 
    -> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");

或(单个语句):

StatementBundle bundle = statementBundleRepository.findById(bundleId)
    .orElseThrow(()
     -> new NotFoundException("Statement bundle with id: " + bundleId + " is not found.");

答案 1 :(得分:1)

Optional类确实提供了一个orElseThrow(...)方法,该方法将Supplier作为唯一参数,因此允许我们在值不存在的情况下抛出自定义异常。

这将启用以下表达式:

StatementBundle bundle = bundleOpt.orElseThrow( ()->new NotFoundException("Statement bundle with id: " + bundleId + " is not found.") );

答案 2 :(得分:0)

请勿操作NoSuchElementException,将其包装在自定义异常中。

try {
    try {
        // We simulate a failing .get() on an Optional.
        throw new NoSuchElementException("message from Optional.get()");
    } catch (NoSuchElementException ex) {
        // We wrap the exception into a custom exception and throw this.
        throw new MyException("my message", ex);
    }
} catch (MyException ex) {
    // Now we catch the custom exception and can inspect it and the
    // exception that caused it.
    System.err.println(ex.getClass().getCanonicalName()
            + ": " + ex.getMessage()
            + ": " + ex.getCause().getMessage());
}

输出:

MyException: my message: message from Optional.get()