What is the difference between Error and Exception in Java?
Both extend Throwable. An Exception represents a problem a program can reasonably catch and handle, while an Error such as OutOfMemoryError signals a serious JVM-level failure that applications normally should not try to recover from.
Explain it simply
If your bike has a puncture, you can fix it and ride on. That is an Exception. If the road itself collapses under you, there is nothing the rider can do. That is an Error.
Example
// Throwable
// |-- Error (JVM problems)
// | |-- OutOfMemoryError
// | |-- StackOverflowError
// |-- Exception
// |-- IOException (checked)
// |-- RuntimeException (unchecked)
// |-- NullPointerException
static int depth = 0;
static void recurse() { depth++; recurse(); }
try {
recurse();
} catch (StackOverflowError e) {
System.out.println("stack overflow caught"); // prints: stack overflow caught
}What to say in the interview
"Throwable is the root, with two branches. Exceptions are checked (IOException) or unchecked (RuntimeException subclasses) and are meant to be handled. Errors such as OutOfMemoryError, StackOverflowError and NoClassDefFoundError come from the JVM, and the compiler does not force me to handle them. I do not normally catch them, though a top-level handler may log them before the application stops."
Common mistakes
- Catching Throwable broadly, which also swallows Errors the application cannot fix.