Exception Vs Error in Java
The general meaning of exception is a deliberate act of omission while the meaning of error is an action that is inaccurate or incorrect. In Java, Exception, and Error both are subclasses of the Java Throwable class that belongs to java.lang package. But there exist some significant differences between them. So, in this section, we are going to discuss the key differences between exception and error.
Before moving ahead in this section let's have a look at the hierarchy of the Java Throwable class.
The term exception is shorthand for the phrase exception event. It is an event that occurs during the execution of the program and interrupts the normal flow of program instructions. These are the errors that occur at compile time and run time. It occurs in the code written by the developers. It can be recovered by using the try-catch block and throws keyword. There are two types of exceptions i.e. checked and unchecked.
There are some important points that should be kept in mind while dealing with the exception:
Advantages of Exceptions
Let's understand the exception through a Java program.
Example of Exception
Let's run the above program and enter a float value deliberately to generate an exception.
It shows the InputMismatchExaception. Because the program accepts an integer value. We observe that the next statement is skipped and the program is terminated.
Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors is OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of the Error class.
Let's understand the error through a Java program.
Example of Error
We observe that on running the program, we get the StackOverflowError, not an exception.
Let's discuss the key differences between exception and error.
Difference Between Exception and Error
In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to java.lang package.