In what situations should one catch java.lang.Error
on an application?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In an Android application I am catching a java.lang.VerifyError. A library that I am using won't work in devices with an old version of the OS and the library code will throw such an error. I could of course avoid the error by checking the version of OS at runtime, but:
Generally you should always catch
java.lang.Error
and write it to a log or display it to the user. I work in support and see daily that programmers cannot tell what has happened in a program.If you have a daemon thread then you must prevent it being terminated. In other cases your application will work correctly.
You should only catch
java.lang.Error
at the highest level.If you look at the list of errors you will see that most can be handled. For example a
ZipError
occurs on reading corrupt zip files.The most common errors are
OutOfMemoryError
andNoClassDefFoundError
, which are both in most cases runtime problems.For example:
can produce an
OutOfMemoryError
but it is a runtime problem and no reason to terminate your program.NoClassDefFoundError
occur mostly if a library is not present or if you work with another Java version. If it is an optional part of your program then you should not terminate your program.I can give many more examples of why it is a good idea to catch
Throwable
at the top level and produce a helpful error message.Very rarely.
I'd say only at the top level of a thread in order to ATTEMPT to issue a message with the reason for a thread dying.
If you are in a framework that does this sort of thing for you, leave it to the framework.
Never. You can never be sure that the application is able to execute the next line of code. If you get an
OutOfMemoryError
, you have no guarantee that you will be able to do anything reliably. Catch RuntimeException and checked Exceptions, but never Errors.http://pmd.sourceforge.net/rules/strictexception.html
And there are a couple of other cases where if you catch an Error, you have to rethrow it. For example ThreadDeath should never be caught, it can cause big problem is you catch it in a contained environment (eg. an application server) :
There is an Error when the JVM is no more working as expected, or is on the verge to. If you catch an error, there is no guarantee that the catch block will run, and even less that it will run till the end.
It will also depend on the running computer, the current memory state, so there is no way to test, try and do your best. You will only have an hasardous result.
You will also downgrade the readability of your code.