我正在尝试从顶级异常中递归查找所有内部异常(getCause 的)...特定实例类型。
public class MyCustomRunTimeException extends RuntimeException {
public MyCustomRunTimeException() {
}
public MyCustomRunTimeException(Exception innerException) {
super(innerException);
}
}
这是我尝试过的:
和我早期的“查找”方法:
private void findAllSpecificTypeOfInnerExceptions(Exception ex)
{
Collection<MyCustomRunTimeException> MyCustomRunTimeExceptions = Stream.iterate(ex, Throwable::getCause)
.filter(element ->
element != null
&& element instanceof MyCustomRunTimeException
)
.map(obj -> (MyCustomRunTimeException) obj)
.collect(Collectors.toList());
}
它不起作用。 :( 我已经尝试了其他几种方法(尚未显示)......如果我得到任何不会引发异常的东西,我会将它们作为“附加”发布到这个问题。 不工作....我收到 NullPointers 异常。和(取决于我的调整)java.lang.reflect.InvocationTargetException 异常。
下面是一些可以找到 1:N“匹配项”的示例。
Exception exampleOne = new MyCustomRunTimeException();
Exception exampleTwo = new Exception(new MyCustomRunTimeException());
Exception exampleThree =new Exception(new Exception(new MyCustomRunTimeException()));
Exception exampleFour =new Exception(new Exception(new MyCustomRunTimeException(new ArithmeticException())));
最佳答案
在这种情况下,我真的认为在循环中执行递归位比完全使用流更简单:
List<Throwable> exlist = new ArrayList<>();
while(ex.getCause()!=null) {
exlist.add(ex.getCause());
ex = ex.getCause();
}
exlist = exlist.stream().filter(e -> e instanceof MyCustomRunTimeException).collect(Collectors.toList());
在 Java 9+ 中有更好的选择,如果你使用外部库,但在核心 Java 8 中不是真的(黑客确实存在,但这使得它比上面的更不清楚,恕我直言,我真的不看到为此目的引入外部库是值得的。)
或者这个变体:
private <T extends Throwable> Collection<T> aggregateSubClassExceptions(Throwable inputEx, Class<T> type) {
Collection<T> returnItems = new ArrayList<>();
Throwable exc = inputEx;
while (exc != null) {
if (type.isInstance(exc)) {
returnItems.add(type.cast(exc));
}
exc = exc.getCause();
}
return returnItems;
}
此代码获取特定类型和任何子类:
Collection<MyCustomRunTimeException> testItOutCollection;
Exception exampleOne = new MyCustomRunTimeException();
Exception exampleTwo = new Exception(new MyCustomRunTimeException());
Exception exampleThree = new Exception(new Exception(new MyCustomRunTimeException()));
Exception exampleFour = new Exception(new Exception(new MyCustomRunTimeException(new ArithmeticException())));
MyCustomRunTimeException exampleFive = new MyCustomRunTimeException(new MySubMyCustomRunTimeException(new MyCustomRunTimeException(new ArithmeticException())));
testItOutCollection = this.aggregateSubClassExceptions(exampleOne, MyCustomRunTimeException.class);
testItOutCollection = this.aggregateSubClassExceptions(exampleTwo, MyCustomRunTimeException.class);
testItOutCollection = this.aggregateSubClassExceptions(exampleThree, MyCustomRunTimeException.class);
testItOutCollection = this.aggregateSubClassExceptions(exampleFour, MyCustomRunTimeException.class);
testItOutCollection = this.aggregateSubClassExceptions(exampleFive, MyCustomRunTimeException.class);
关于java - 在所有内部异常中查找特定类型的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57329034/