1

Lets take this example

public MyClass{
    public void myMethod() throws ExceptionC{
        try{
            //some method calll throwing ExceptionA, ExceptionB
        }catch(ExceptionA | ExceptionB e){
            throw new ExceptionC(e);
        }
    }
}

So I bubble up any of ExceptionA or ExceptionB into higher level as ExceptionC. So I am going to use myClass.myMethod() as follows.

try{
    MyClass myclass = new MyClass();
    myclass.myMethod();
}catch(Exception C){
    //I want to find whether ExceptionC happened from ExceptionA or ExceptionB????
}

So as my code comment suggests //I want to find whether ExceptionC happened from ExceptionA or ExceptionB????

Can someone please explain, how can I do that?

(Please don't take the famous checked-exceptions-good-or-bad war into here.)

Supun Wijerathne
  • 11,964
  • 10
  • 61
  • 87
  • 1
    http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#getCause--. You may have to call it more than once. – ajb Aug 05 '16 at 03:31
  • @ajb thnx for the reference. And what do you mean by more than once? – Supun Wijerathne Aug 05 '16 at 03:34
  • 2
    I mean, the exception (or `Throwable`) returned by `getCause()` may itself be a wrapper that has its own `getCause()`. You'll need to decide whether this is a possibility. But when I've written unit tests that test an exception's cause, I use a loop, because there are lots of things around our code that can wrap exceptions. – ajb Aug 05 '16 at 03:36
  • 1
    since your example is "MyClass" i'll assume you own MyClass and would recommend against wrapping the causedBy Exception in the first place unless there's a strong reason for doing so. While it was worse 10+ years ago when Java didn't even support a "wrapping" Exception in the JDK (and root causes were often lost), don't wrap for the hell of it and avoid the problem you describe altogether – jamey graham Aug 05 '16 at 03:45

0 Answers0