Example & Tutorial understanding programming in easy ways.

What is the difference between Error and Exception?

The main difference between Error  and exception are as follows:

 1) Main difference on Error vs Exception is that Error is not meant to catch as even if you catch it you can not recover from it. For example during OutOfMemoryError, if you catch it you will get it again because GC may not be able to free memory in first place. On the other hand Exception can be caught and handled properly.

2) Error are often fatal in nature and recovery from Error is not possible which is different in case of Exception which may not be fatal in all cases.

3) Unlike Error, Exception is generally divided into two categories e.g. checked and unchecked Exceptions. Checked Exception has special place in Java programming language and require a mandatory try catch finally code block to handle it. On the other hand Unchecked Exception, which are subclass of RuntimeException mostly represent programming errors. Most common example of unchecked exception is NullPointerException in Java.

4) Similar to unchecked Exception, Error in Java are also unchecked. Compiler will not throw compile time error if it doesn't see Error handled with try catch or finally block. In fact handling Error is not a good Idea because recovery from Error is mostly not possible.

These are the major difference between Error and Exception in Java. key point to remember is that Error are fatal in nature and recovery may not be possible, on the other hand by carefully handling Exception you can make your code more robust and guard against different scenarios. But you need to be more careful in the case of error, they are not recoverable at all.

Read More →