Here in this article you will learn about difference between error and exception in java.
In exception hierarchy we need to see where these two classes exist. Throwable Class is the root for the Java Exception Hierarchy. Throwable contains two chain of classes, Exception and Error.
Exceptions | Errors |
Mostly because of our programs. | These occur because of lack of system resources. |
Exceptions are recoverable. | Errors are not recoverable. |
Exceptions can be handled using try catch blocks. | Errors cannot be handled using try catch blocks. |
Exceptions can be Compile-time (checked) or Run-time (Unchecked). | Errors are always Run-time (Unchecked). |
Exceptions can be handled by the programmer. | Errors need to be handled by the System Administrator. |
Example, if our program requires to read data from a remote file located at a different destination, and we are not able to access that destination, we will get a FileNotFoundException. | Example, if our program requires to load some large data in memory, and then we can get an OutOfMemoryError. |
Examples of checked Exceptions are: ParseException, FileNotFoundException. Examples of Unchecked Exceptions are: ArrayIndexOutOfBoundException, ClassCastException | Examples of unchecked Exceptions are: OutOfMemoryError, StackOverflowError, etc. |
Suppose that we want to write a program to output the division of two numbers.
public class ExceptionExample { public static void main(String args[]){ int denominator = 0; int numerator = 20; int fraction = numerator/denominator; System.out.println(fraction); System.out.println("Main method ends here."); } }
When we run this, we get the following Exception.
Exception in thread “main” java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:5) Process finished with exit code 1
We can see that the last statement in main does not executes. To resolve this we can apply a try catch block to catch the division by zero exception.
public class ExceptionExample { public static void main(String args[]){ int denominator = 0; int numerator = 20; try { int fraction = numerator/denominator; System.out.println(fraction); } catch (ArithmeticException e) { System.out.println("In the catch block due to Exception " + e); } System.out.println("Main method ends here."); } }
Here, we have included the statements that were causing the exception in a try block, and then catch them using a catch block. When we run this, we get the following output:
In the catch block due to Exception java.lang.ArithmeticException: / by zeroMain method ends here. Process finished with exit code 0
Since we have handled the exception, we get the last statement printed. This is how exception handling works.