java - 将受检异常与 java.util.function.Predicate 一起使用

标签 java exception functional-programming predicate

谓词是自 1.8 以来引入的一个很棒的概念。他们提供的组合(和/或)以及其他功能确实让生活变得更轻松。

我已经广泛使用它们有一段时间了,直到最近我陷入了与异常处理有关的用例之一(对于已检查的异常):

背景: 我希望我的谓词实现能够抛出一些已检查的异常,调用者应该能够捕获这些异常并进行相应的操作。 (一些PredicateExecutionFailedException)。由于 JDK 的 java.util.Predicate 定义中没有抛出此类异常,因此我无法从我的实现中抛出任何此类异常。我觉得这是一个缺失的部分,它可以为调用谓词的客户端提供更多的灵活性。以下是 JDK 1.8 的片段。

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *

问题: 有什么解决方法吗?我只想捕获已检查的异常(不应捕获 RuntimeException)。我无法理解这个问题。欢迎提出任何建议。

最佳答案

检查异常没有特定的父异常类,就像我们为所有运行时异常 RuntimeException.class 有一个特定的父异常类一样。 所以也许你可以像下面这样使用。

try {
//write our business logic 
} catch(RuntimeException e ){
 throw e ;
} catch(Exception e){
 // You can catch only checked exception here now
}   

也可以有其他方式

关于java - 将受检异常与 java.util.function.Predicate 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58395054/

相关文章:

java - 使用比较器时如何排除字符串

java - 我的 REST 方法应该有一个单独的 Controller 吗?

Javascript 嵌套异常处理

algorithm - 控制流异常

haskell - 如何从纯函数中调用不纯函数?

java - 映射getOrDefault VS getOrUseSupplier

java - JPanel组件绘制顺序

java.util.AbstractMap.equals() : what is it for try/catch?

scala - 为什么更喜欢 Typeclass 而不是 Inheritance?

java - Java中如何解决NumberFormatException?