Search code examples
javaexceptionnosuchmethoderror

Java - NoSuchMethodError not caught by Exception


I was under the impression that Exception is good for catching all possible exceptions since every one of them has Exception as a base class. Then while developing an Android app I used the following method which in some custom ROMs has been removed.

boolean result = false;
try{
   result =  Settings.canDrawOverlays(context);
}
catch(Exception e){
    Log.e("error","error");
}

However this did not catch the exception thrown. Later I used NoSuchMethodError instead of Exception and then the exception was caught.

Can someone explain why this is happening ?


Solution

  • Java exception hierarchy looks like so:

    Throwable
     |      |
    Error   Exception
            |
            RuntimeException
    

    Errors are intended for signaling regarding problems in JVM internals and other abnormal conditions which usually cannot be handled by the program anyhow. So, in your code you are not catching them. Try to catch Throwable instead:

    boolean result = false;
    try{
       result =  Settings.canDrawOverlays(context);
    }
    catch(Throwable e){
        Log.e("error","error");
    }
    

    Also it's a good idea to read this