Question of the Week #41
What is the purpose of the Error class and how is it different from Exception?
3 messages · Page 1 of 1 (latest)
What is the purpose of the Error class and how is it different from Exception?
Similar to Exception, instances of Error can be thrown and contain a stack trace which can be used for finding the root cause.
Java throws Errors for errors that can (typically) not be recovered from.
Examples of that includes OutOfMemoryError (in case an object allocation fails due to not sufficient memory being available), StackOverflowError or NoClassDefFoundError (in case a class attempted to use another class which doesn't exist or could not be loaded).
On the other hand, Exceptions are used for other errors that may occur in a program.
In contrast of Error, instances of Exception (unless they are an instance of RuntimeException) need to be handled when calling code that could throw them.
Developers should neither create subclasses of Error nor manually throw instances of Error using the throw statement nor catch Errors.
Instead, developers should try to make sure that Errors don't happen when running their applications.
Errors are serious, unrecoverable issues that are outside the control of the application. For example an OutOfMemoryError can happen if the application needs more memory than the system can process - public class OutOfMemoryExample {
public static void main(String[] args) {
try {
int[] array = new int[Integer.MAX_VALUE];
} catch (OutOfMemoryError error) {
System.out.println("Oops! Out of memory error occurred.");
error.printStackTrace();
}
}
} while exceptions are for handling conditions that the application could possibly recover from. A type of exception would be FileNotFoundException. import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileReadExample {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("nonexistent.txt");
} catch (FileNotFoundException exception) {
System.out.println("Oops! File not found.");
exception.printStackTrace();
}
}
}