### Question:
CbThrowables { public static <T extends Throwable> Optional<T> findCause(Throwable t, final Class<T> type) { for (; t != null; t = t.getCause()) { if (type.isAssignableFrom(t.getClass())) { return Optional.of(type.cast(t)); } } return Optional.empty(); } private  CbThrowables(); static Optional<T> findCause(Throwable t, final Class<T> type); static boolean hasCause(Throwable t, final Class<? extends Throwable> type); static void throwIfUnchecked(Throwable t); static void throwIfInstanceOf(Throwable t, Class<T> clazz);  }### Answer:
@Test void findsNearestCause() { Optional<IllegalArgumentException> result = CbThrowables.findCause( new RuntimeException( new IllegalArgumentException("foo", new IllegalArgumentException("bar"))), IllegalArgumentException.class); assertTrue(result.isPresent()); assertEquals("foo", result.get().getMessage()); }
@Test void findRoot() { Optional<IllegalArgumentException> result = CbThrowables.findCause( new IllegalArgumentException("foo", new IllegalArgumentException("bar")), IllegalArgumentException.class); assertTrue(result.isPresent()); assertEquals("foo", result.get().getMessage()); }
@Test void findBySuperclass() { Optional<RuntimeException> result = CbThrowables.findCause( new Exception("foo", new IllegalArgumentException("foo")), RuntimeException.class); assertTrue(result.isPresent()); assertEquals(IllegalArgumentException.class, result.get().getClass()); assertEquals("foo", result.get().getMessage()); }