Week 41 — What is the purpose of the `Error` class and how is it different from `Exception`?
Question of the Week #41
What is the purpose of the
Error
class and how is it different from Exception
?3 Replies
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 Error
s 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, Exception
s 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 Error
s.
Instead, developers should try to make sure that Error
s don't happen when running their applications.📖 Sample answer from dan1st
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();
}
}
}
Submission from kacieatdvm
Error
Error is type of throwable object which can occur during the execution of a program and there's no way to handle it. Programmers can only try their best to prevent it. Once it occurs the execution of the program is stopped.
Few common types of errors are
StackOverflowError
, OutOfMemoryError
This code is going to produce StackOverflowError
Exception
Exception is also a type of throwable object but the difference is it can be caught and handled within a program. So it can prevent the program from crashing and instead can print a informative error message.
Few common types of exceptions are
NullPointerException
, IOException
This code will throw a NullPointerException
but we are catching and handling it properly which will prevent our program from crashing.⭐ Submission from vampzofficial