谓词是从1.8引入的一个很棒的概念。它们所提供的组合(和/或)以及其他特性确实使生活变得更容易。
有一段时间以来,我一直在广泛地使用它们,直到最近我才开始使用其中一个关于异常处理的用例(用于检查异常):
背景:我希望我的谓词实现能够抛出一些检查过的异常,调用者应该能够捕获这些异常并对其采取相应的行动。(一些PredicateExecutionFailedException)。由于JDK的java.util.Predicate定义中没有这样的异常,所以我不能从我的实现中抛出任何这样的异常。我觉得这是一个缺失的部分,它会给调用谓词的客户端提供更多的灵活性。下面是JDK1.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 )。我没法把头绕到这上面。欢迎任何建议。
发布于 2019-10-15 13:17:23
对于选中的异常,没有特殊的父异常类,比如对于所有运行时异常RuntimeException.class,我们都有一个特定的父异常。所以也许你可以像下面这样使用。
try {
//write our business logic
} catch(RuntimeException e ){
throw e ;
} catch(Exception e){
// You can catch only checked exception here now
} 还有其他的方法
发布于 2019-10-15 14:03:57
子类和实现类的方法不能抛出比它们覆盖或实现的方法更多的检查异常,因为这将违反Liskov代换原理。原因是根据接口,不需要调用accept来处理异常,因此现有的实现不能被某些要求调用方处理异常的实现所替代。Java编译器强制执行此约束。
典型的解决方案是将异常重新映射到特定的RuntimeException子类型,这样就可以以多形性的方式捕获异常,而不必冒捕获像NullPointerException这样的事情的风险。这意味着:
定义您自己的异常:
class PredicateExecutionFailedException extends RuntimeException {
/* Implementation */
}在Predicate实现中映射所需的异常:
public boolean test(String t)
{
try {
/* Something */
}
catch( SomeException e )
{
throw new PredicateExecutionFailedException(e);
}
}然后酌情在PredicateExecutionFailedException子句中声明catch类型。
https://stackoverflow.com/questions/58395054
复制相似问题