Both java.lang.Error and java.lang.Exception classes are sub classes of java.lang.Throwable class
1. java.lang.Error class represents the errors which are mainly caused by the environment in which application is running.
- Errors are irrecoverable
- Errors cannot be handled, only way is to terminate execution.
- Errors are related to environment in which application is running.
For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows.
2. java.lang.Exception class represents the exceptions which are mainly caused by the application itself.
- Exceptions can be handled
- Exceptions can be handled using try-catch or we can use throw to handle it on caller side and can make program flow normal if they happen.
- Exceptions are related to application.
For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types.
Compiler will not have any knowledge about unchecked exceptions which include Errors and sub classes of RunTimeException because they happen at run time and where as compiler will have knowledge about checked Exceptions. Compiler will force you to keep try-catch blocks if it sees any statements which may throw checked exceptions.