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
Almost never. Errors are designed to be issues that applications generally can't do anything about. The only exception might be to handle the presentation of the error but even that might not go as planned depending on the error.
Ideally we should not handle/catch errors. But there may be cases where we need to do, based on requirement of framework or application. Say i have a XML Parser daemon which implements DOM Parser which consumes more Memory. If there is a requirement like Parser thread should not be died when it gets OutOfMemoryError, instead it should handle it and send a message/mail to administrator of application/framework.
ideally we should never catch Error in our Java application as it is an abnormal condition. The application would be in abnormal state and could result in carshing or giving some seriously wrong result.
An
Error
usually shouldn't be caught, as it indicates an abnormal condition that should never occur.From the Java API Specification for the
Error
class:As the specification mentions, an
Error
is only thrown in circumstances that are Chances are, when anError
occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such asVirtualMachineError
)Although an
Error
is a subclass ofThrowable
which means that it can be caught by atry-catch
clause, but it probably isn't really needed, as the application will be in an abnormal state when anError
is thrown by the JVM.There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.