Both Error and Exception are derived from java.lang.Throwable in Java but main difference between Error and Exception is kind of error they represent. java.lang.Error represent errors which are generally can not be handled and usually refer catastrophic failure e.g. running out of System resources, some examples of Error in Java are java.lang.OutOfMemoryError or Java.lang.NoClassDefFoundError and java.lang.UnSupportedClassVersionError. On the other hand java.lang.Exception represent errors which can be catch and dealt e.g. IOException which comes while performing I/O operations i.e. reading files and directories. Clear understanding of Error and Exception is must for any serious Java programmer and good programming and debugging skills are required to overcome issues which caused Error and Exception in Java. Apart from its must have knowledge in Java application development, difference between Error and Exception is also a popular questions on Java interviews related to Exception handling, similar to difference between throw and throws in Java. In this Java article we will briefly see major difference between Error and Exception in Java which include both syntactical and logical difference.
Error vs Exception in Java
Here is my list of notable difference between Error vs Exception in Java.
1) As I said earlier, 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.
That's all on 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.
Other Java Interview Questions you may like