Site icon

What is difference between error & exception in java (class hierarchy/ example)

1. Exception class hierarchy in java

Fig 1: Errors & exceptions class hierarchy in java

2. Difference between errors & exceptions in java (examples)

No.Error Exception
1Errors occur in an application due to lack of system resources.
For example:
StackOverflowError occurs, when stack size is exhausted or NoClassDefFoundError occurs when particular class is not available or OutOfMemoryError occurs when JVM does not have enough memory
Exception occurs in an application mostly due to programming mistakes.
For example:
ClassCastException occurs, when we try to cast incompatible classes or ArrayIndexOutOfBoundsException occurs, when we try to access the array index beyond its bounds.
2We can catch the error conditions, but we can not recovers from error conditions.
For example:
If OutOfMemoryError occurred, we just cannot recover from it. We can catch the error just for logging purpose etc.
We can catch the exceptions using catch blocks and recover from them.
For example:
If ArrayIndexOutOfBoundsException occurs, in catch block we can introspect the error condition, correct the exception condition and resume the normal flow of application.
Exit mobile version