Middle
What type of exception in Java cannot be handled?
sobes.tech AI
Answer from AI
Error. These are serious problems that cannot be reasonably recovered from in an application, such as memory exhaustion (OutOfMemoryError) or stack overflow (StackOverflowError). They indicate critical failures in the Java Virtual Machine (JVM) environment.
Unlike Exception (which can be checked or unchecked), Error should only be caught in exceptional cases (for example, during logging), but not for continuing normal program operation.
Example:
// This code demonstrates Error,
// but catching Error in production is generally not recommended
try {
// Attempt to trigger OutOfMemoryError (may not work depending on JVM settings)
List<byte[]> list = new ArrayList<>();
while (true) {
list.add(new byte[1024 * 1024]); // Allocate a lot of memory
}
} catch (OutOfMemoryError e) {
// Logging or attempt to terminate
System.err.println("Critical error: insufficient memory!");
e.printStackTrace();
// Usually, emergency shutdown logic is executed here
}