Working on Android I bumped into something like this:
    try {
         return someMethodThatThrowsExceptionA();
        } catch (ExceptionBthatExtendsExceptionA e) {
            // e is null but caught here.
        } catch (ExceptionA e) {
            // e is also null when caught.
        }
    }
While I still need to dig out the reasons why the exception is thrown inside many method calls, there are two very surprising things here for me:
- The Exceptionis caught, but somehow isnull. As per A and B , I thought that throwingnullwas impossible.
- The Exceptionis catched by acatch blockfor aSubclassof theExceptionthat the method throws (ExceptionBthatExtendsExceptionA).
If I remove the catch block for ExceptionBthatExtendsExceptionA, the Exception is caught by the ExceptionA catch block, but is also null.
Could you explain me
- How a methodis throwingnullwithout creating aNullPointerException? ----> Not possible as per Java's specification.
- How is a nullExceptioncorrectly catched (casted?) to a specificcatch block? How can can thecatch blockrecognize thatnullis an instance of aSubclassand not of its parentClass? ----> Same as question before.
- Are these allowed Javabehaviors or is this maybe a bug related toAndroid StudioorDalvik/ART? ----> Possibly.
Edit:
It seems that this is a bug for the debugger in Android Studio 1.4.
After debugging and testing with different devices I've found this:
- The error doesn't happen when not debugging the app.
- It also doesn't present when debugging or not on Lollipopdevices.
- It has only been present when debugging 4.3or4.4devices so far, if I unplug the device, the app behaves as expected.
As more information for the implementation, the try/catch block described before is inside an AsyncTask's doInBackground(), and someMethodThatThrowsExceptionA() is a method constructs a query and calls internally a method that executes a Fusiontables.Query.Sql and throws ExceptionA , in this case IOException and it's subclass UserRecoverableAuthIOException (ExceptionBthatExtendsExceptionA) , so Http communications happen inside.
Also, when I try to catch the error inside someMethodThatThrowsExceptionA(), sometimes the Exception catched is not null, but it always ends up being null when I throw it again and catch it in the catch block of method that called someMethodThatThrowsExceptionA().
Since the Exception is correctly interpreted as an instance of UserRecoverableAuthIOException (ExceptionBthatExtendsExceptionA) and the code enters into its corresponding catch block, the bug has to be happening after this and before the debugger figures out the value of the exception inside the block.
 
    