ExceptionUtils { public static <T extends Throwable, C extends Class<T>> T matchPath(Throwable ex, C returnClass, Class<?>... cs) { ArrayList<Class<?>> classList = new ArrayList<Class<?>>(cs.length); classList.addAll(Arrays.asList(cs)); Collections.reverse(classList); for (Class<?> next : classList) { Throwable nextEx = ex.getCause(); if (! (nextEx != null && next.isInstance(nextEx))) { return null; } ex = nextEx; } Throwable nextEx = ex.getCause(); if (! (nextEx != null && returnClass.isInstance(nextEx))) { return null; } return returnClass.cast(nextEx); }  static T matchPath(Throwable ex, C returnClass,
	    Class<?>... cs);  }
@Test public void testMatchPath() { Throwable root = new NullPointerException(); Throwable ex = new InvalidAlgorithmParameterException(root); ex = new InvalidPropertiesFormatException(ex); NullPointerException result = ExceptionUtils.matchPath(ex, NullPointerException.class, InvalidAlgorithmParameterException.class); Assert.assertNotNull(result); Assert.assertEquals(result, root); }