When to Catch Error: Almost Never
You'll learn why catching Error instances is almost always the wrong approach in Java applications.
The Core Idea
In the previous lesson, you learned that Java's exception hierarchy splits into two branches: Exception (for recoverable problems) and Error (for serious, system-level failures). Error and its subclasses represent catastrophic conditions that your application cannot and should not try to handle.
Common Error subclasses include:
OutOfMemoryError– The JVM has run out of memoryStackOverflowError– The call stack is exhausted (usually from infinite recursion)VirtualMachineError– The JVM itself is broken or corrupted
Why Not Catch Errors?
Think of Error like a building's fire alarm. When it sounds, you don't try to "handle" it by turning off the alarm and continuing work—you evacuate. Similarly, when an Error occurs, the JVM is telling you: "I cannot guarantee correct behavior anymore."
If you catch an OutOfMemoryError and try to continue, what happens? Your program is already out of memory—any further operations will likely fail unpredictably or corrupt data.
If you catch a StackOverflowError, the stack is exhausted. Even the catch block itself needs stack space to execute!
The Exception to the Rule
The only legitimate reason to catch Error is for logging or cleanup during application shutdown—and even then, you should immediately rethrow or terminate, never attempt recovery.
Key Takeaway:
Error instances represent unrecoverable system failures; catching them in application code prevents proper failure diagnosis and can lead to data corruption. Let them propagate to terminate the program cleanly.