Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching an exception that is nested into another exception

People also ask

How do you handle nested exceptions?

Exception handling begins again with the most recently generated exception. Note: If a nested exception causes the program to end, the exception handler for the first exception may not complete. In this example, the main() function generates an exception which causes main_hdlr to get control.

How do you handle nested exceptions in Java?

In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try. In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero.

How do you resolve a nested try catch?

How to Avoid the Nesting? Extracting the nested part as a new method will always work for any arbitrarily nested Try-Catch-Finally block. So this is one trick that you can always use to improve the code.

How can you catch an exception thrown by another thread?

There does not exist a way in Java to use try/catch around your start() method to catch the exceptions thrown from a secondary thread and remain multithreaded.


The ExceptionUtils#getRootCause() method can come in very handy in such situations.


There is no more elegant way of selectively "catching" nested exceptions. I suppose if you did this kind of nested exception catching a lot, you could possibly refactor the code into a common utility method. But it still won't be either elegant or efficient.

The elegant solution is to do away with the exception nesting. Either don't chain the exceptions in the first place, or (selectively) unwrap and rethrow the nested exceptions further up the stack.

Exceptions tend to be nested for 3 reasons:

  1. You have decided that the details of the original exception are unlikely to be useful for the application's error recovery ... but you want to preserve them for diagnostic purposes.

  2. You are implementing API methods that don't allow a specific checked exception but your code unavoidably throws that exception. A common workaround is to "smuggle" the checked exception inside an unchecked exception.

  3. You are being lazy and turning a diverse set of unrelated exceptions into a single exception to avoid having lots of checked exceptions in your method signature1.

In the first case, if you now need to discriminate on the wrapped exceptions, then your initial assumptions were incorrect. The best solution is change method signatures so that you can get rid of the nesting.

In the second case, you probably should unwrap the exceptions as soon as control has passed the problematic API method.

In the third case, you should rethink your exception handling strategy; i.e. do it properly2.


1 - Indeed, one of the semi-legitimate reasons for doing this has gone away due to the introduction of the multi-exception catch syntax in Java 7.

2 - Don't change your API methods to throws Exception. That only makes things worse. You now have to either "handle" or propagate Exception each time you call the methods. It is a cancer ...


You should add some checks to see if e.getCause().getCause() is really a MyException. Otherwise this code will throw a ClassCastException. I would probably write this like:

} catch(RemoteAccessException e) {
    if(e.getCause() != null && e.getCause().getCause() instanceof MyException) {
        MyException ex = (MyException)e.getCause().getCause();
        // Do further useful stuff
    } else {
        throw new IllegalStateException("...");
    }
}

I just solved a problem like this by writing a simple utility method, which will check the entire caused-by chain.

  /**
   * Recursive method to determine whether an Exception passed is, or has a cause, that is a
   * subclass or implementation of the Throwable provided.
   *
   * @param caught          The Throwable to check
   * @param isOfOrCausedBy  The Throwable Class to look for
   * @return  true if 'caught' is of type 'isOfOrCausedBy' or has a cause that this applies to.
   */
  private boolean isCausedBy(Throwable caught, Class<? extends Throwable> isOfOrCausedBy) {
    if (caught == null) return false;
    else if (isOfOrCausedBy.isAssignableFrom(caught.getClass())) return true;
    else return isCausedBy(caught.getCause(), isOfOrCausedBy);
  }

When you use it, you would just create a list of if's from most specific Exception to least specific, with a fallback else-clause:

try {
  // Code to be executed
} catch (Exception e) {
  if (isCausedBy(e, MyException.class)) {
    // Handle MyException.class
  } else if (isCausedBy(e, AnotherException.class)) {
    // Handle AnotherException.class
  } else {
    throw new IllegalStateException("Error at calling service 'service'");
  }
}

Alternative/Addition per requests in comments

If you want to use a similar method to get the Exception object of the class you're looking for, you can use something like this:

  private boolean getCausedByOfType(Throwable caught, Class<? extends Throwable> isOfOrCausedBy) {
    if (caught == null) return null;
    else if (isOfOrCausedBy.isAssignableFrom(caught.getClass())) return caught;
    else return getCausedByOfType(caught.getCause(), isOfOrCausedBy);
  }

This could be used in addition to isCausedBy() this way:

  if (isCausedBy(e, MyException.class)) {
    Throwable causedBy = getCausedBy(e, MyException.class);
    System.err.println(causedBy.getMessage());
  }

It can also used directly instead of isCausedBy(), although it's probably a matter of opinion whether this is more readable.

  Throwable causedBy;
  if ((causedBy = getCausedBy(e, IllegalAccessException.class)) != null) {
    System.err.println(causedBy.getMessage());
  }