Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - NoSuchMethodError not caught by Exception [duplicate]

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 ?

like image 695
Anonymous Avatar asked Jul 09 '16 15:07

Anonymous


People also ask

What causes Java Lang NoSuchMethodError?

NoSuchMethodError is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang. OutOfMemoryError .

Can you catch the same exception twice in Java?

Java does not allow us to catch the exception twice, so we got compile-rime error at //1 .

What happens if an exception is not caught in a method Java?

What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.


1 Answers

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

like image 186
Pavel S. Avatar answered Oct 15 '22 03:10

Pavel S.