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 ?
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 .
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? 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With