Tag: 嵌套exception

检查某个exception类型是否是嵌套exception中的原因(原因等等)的最佳方法?

我正在编写一些JUnit测试,以validation是否抛出了类型MyCustomException的exception。 但是,此exception多次包含在其他exception中,例如InvocationTargetException,而InvocationTargetException又包含在RuntimeException中。 什么是确定MyCustomException是否以某种方式导致我实际捕获的exception的最佳方法? 我想做这样的事情(见下划线): try { doSomethingPotentiallyExceptional(); fail(“Expected an exception.”); } catch (RuntimeException e) { if (!e. try { doSomethingPotentiallyExceptional(); fail(“Expected an exception.”); } catch (RuntimeException e) { if (!e. e.wasCausedBy (MyCustomException.class) fail(“Expected a different kind of exception.”); } (MyCustomException.class) fail(“Expected a different kind of exception.”); } 我想避免调用getCause()一些“层”深层,以及类似的丑陋的解决方法。 有更好的方式吗? (显然,Spring有NestedRuntimeException.contains(Class) ,它可以做我想要的 – 但我没有使用Spring。) 关闭:好的,我想有一个实用方法真的没有绕过:-)感谢所有回复的人!

捕获嵌套到另一个exception中的exception

我想捕获一个exception,它嵌套到另一个exception中。 我这样做是这样的: } catch (RemoteAccessException e) { if (e != null && e.getCause() != null && e.getCause().getCause() != null) { MyException etrp = (MyException) e.getCause().getCause(); … } else { throw new IllegalStateException(“Error at calling service ‘service'”); } } 有没有办法更有效和优雅地做到这一点?