Interview #129: Java: What is difference between exception and error?
In Java, both Exception and Error are subclasses of the Throwable class. While they may seem similar because they represent problems that occur during the execution of a program, they serve different purposes and are handled differently. Understanding the distinction between them is crucial for effective error handling and robust application design.
Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245
1. Hierarchy of Throwable
In Java, the Throwable class is the superclass of all errors and exceptions. It has two direct subclasses:
Throwable
/ \
Error Exception
2. What is an Exception?
An Exception indicates an event that disrupts the normal flow of a program’s instructions. These are conditions that a well-written application should anticipate and handle, using try-catch blocks or throws declarations.
Types of Exceptions:
Examples:
Examples:
Code Example:
try {
FileReader file = new FileReader("data.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
This is a checked exception, and must be handled or declared.
3. What is an Error?
An Error is a serious issue that typically indicates a problem with the JVM or system resources, and the application should not attempt to handle it. Errors are usually fatal and cannot be recovered from during program execution.
Recommended by LinkedIn
Common Examples of Errors:
Code Example:
public class StackOverflowExample {
public static void recursiveCall() {
recursiveCall(); // Causes StackOverflowError
}
public static void main(String[] args) {
recursiveCall();
}
}
Even though you could technically catch an Error, it's not recommended, as it usually signifies a condition that the program shouldn't try to fix.
4. Key Differences
5. When Should You Use Which?
6. Can Errors Be Caught?
Technically, yes, both Exception and Error can be caught using a catch(Throwable t) block, but catching Error is highly discouraged because:
Conclusion
To summarize:
Understanding the distinction helps in writing robust, fault-tolerant, and well-structured Java applications. While exceptions are part of normal application flow (especially checked ones), errors are more of a signal that something fundamentally has gone wrong, and often require attention from developers or system administrators rather than application-level error handling.