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

  • We will discuss the difference between error & exception in java.
  • We will demonstrate exception class hierarchy in java.
    • We have shown checked & unchecked exception class hierarchy in Fig 1..
  • We will discuss the examples of error & exceptions in java.

1. Exception class hierarchy in java

  • We have shown some of the concrete classes of exceptions in Fig 1.
  • java.lang.Throwable is base class for all types of exceptions (and errors).
Error exception class hierarchy java example
Fig 1: Errors & exceptions class hierarchy in java
  • Broadly the exceptions are categorized into two parts (Refer Fig 1 for checked and unchecked exceptions)
    1. Unchecked exceptions
      • Sub classes of Error and RuntimeException are unchecked exceptions.
    2. Checked exceptions
      • Except Unchecked exceptions, rest of all exceptions are checked exceptions.
  • The Errors are unchecked exceptions.
  • All the errors are under package java.lang.Error
    • e.g. AssertionError, VirtualMachineErrors, LinkageErrors

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.
Scroll to Top