Skip to main content
  1. Posts/

Helpful utility for searching a Java exception chain for a particular exception type

·189 words·1 min
Author
Christopher Taylor
A collection of interesting things I’ve seen, as I’ve seen them.

Sometimes I want to search a chain of exceptions (caught->cause1->cause2…) for an exception of a particular type. This isn’t a difficult problem, but having a simple utility makes it easier:

 1public class SearchCausesFor<T extends Throwable>
 2{
 3    private Class<T> target;
 4    
 5    private SearchCausesFor ( Class<T> target )
 6    {
 7        this.target = target;
 8    }
 9    
10    public static <T extends Throwable> SearchCausesFor<T> SEARCH ( Class<T> target )
11    {
12        if ( target == null ) throw new IllegalArgumentException ( "target is null" );
13        return new SearchCausesFor<T> ( target );
14    }
15 
16    public T IN ( Throwable source )
17    {
18        if ( source == null ) return null;
19        if ( target == null ) throw new IllegalStateException ( "target is null" );
20        if ( target.isInstance( source ) ) return target.cast(source); 
21        return IN ( source.getCause() );
22    }
23}

It’s pretty easy to use:

1try
2{
3  ... // some code that throws an exception
4}
5catch ( RootExceptionType oops )
6{
7  ExceptionTypeIWant wanted = SearchCausesFor.SEARCH(ExceptionTypeIWant.class).IN(oops);
8  if ( wanted != null ) // do something with wanted
9}

Related