Difference Between Error And Exception In Java with Examples
Exception: An unwanted unexpected event that disturbs the normal flow of the program is called an exception.
Example: ElectricityFailureException FileNotFoundException ...etc It is highly recommended to handle exceptions. The main objective of exception handling is graceful (normal) termination of the program.
Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed.
Throwable acts as a root for exception hierarchy.
The throwable class contains the following two child classes.
Similarities Between Error and Exception
1. Error and Exception are subclasses of the Throwable class.
2. Error and Exception can occur at runtime.
Difference Between Error And Exception
1). Occurrence
Exceptions can occur at compile time(checked) or runtime(unchecked),
NullPointerException is a runtime exception on the other hand IOException is a compile-time exception.
Errors occur only at runtime. They are not known to the compiler. e.g AssertionError
2). Recovery
Programs can be recovered by using exception handling mechanism, try-catch block or throw keyword in java.
Programs can not recover from Errors once they occur. Errors will abnormally terminate the program.
3). Package
Exceptions are present in java.lang.Exception package.
Errors are present in java.lang.Error package.
4). Checked and Unchecked
Exceptions can be Checked(compile-time exceptions) or Unchecked exceptions(runtime exceptions). You can find the difference between Checked and Unchecked Exception here.
Errors are a part of Unchecked exceptions in java.
5). Cause
Exceptions are caused by the program/application itself.
Errors are caused by the environment in which the program runs.
6). Examples
Checked Exception examples are IOException, SQLException, etc Unchecked Exception examples are IllegalStateException, ArrayIndexOutOfBoundException etc.
Errors examples are java.lang.OutOfMemoryError, java.lang.StackOverflowError etc.
Example of Error and Exception in Java
StackOverFlowError
It is the child class of Error and hence it is unchecked. Whenever we are trying to invoke recursive method call JVM will raise StackOverFloeError automatically.
public class Test {
public static void methodOne() {
methodTwo();
}
public static void methodTwo() {
methodOne();
}
public static void main(String[] args) {
methodOne();
}
}
output:
Run time error: StackOverFloeError
In this article, we have seen the Difference Between Error And Exception In Java with Examples.
0 Comments
Post a Comment