Java - NoSuchMethodError not caught by Exception [duplicate]
Asked Answered
B

1

12

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 ?

Brachylogy answered 9/7, 2016 at 15:40 Comment(0)
Z
25

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

Zhang answered 9/7, 2016 at 15:43 Comment(2)
aaaw ok...I assumed that NoSuchMethodError was extending Exception. Thumbs up for the graphics. thank you.Brachylogy
same here. always thought exception is the base. guess throwable is the best thing to catchAssimilative

© 2022 - 2024 — McMap. All rights reserved.