title: Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception?
body: <p>I am writing some JUnit tests that verify that an exception of type <code>MyCustomException</code> is thrown. However, this exception is wrapped in other exceptions a number of times, e.g. in an InvocationTargetException, which in turn is wrapped in a RuntimeException.</p>
  <p>What's the best way to determine whether MyCustomException somehow caused the exception that I actually catch? I would like to do something like this (see underlined):</p>
  <pre><code>
  try {
      doSomethingPotentiallyExceptional();
      fail("Expected an exception.");
  } catch (RuntimeException e) {
       if (!e.</code>wasCausedBy<code>(MyCustomException.class)
          fail("Expected a different kind of exception.");
  }
  </code></pre>
  <p>I would like to avoid calling <code>getCause()</code> a few &quot;layers&quot; deep, and similar ugly work-arounds. Is there a nicer way?</p>
  <p>Apparently, Spring has <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/core/NestedRuntimeException.html" rel="nofollow noreferrer">NestedRuntimeException.contains(Class)</a>, which does what I want - but I'm not using Spring.</p>