Errors vs Exceptions

ERROR

EXCEPTION

Basic

caused due to a lack of system resources

caused because of the code

Recovery

irrecoverable

recoverable

Keywords

no means to handle an error by the program code

handled using three keywords “try”, “catch”, and “throw

Consequences

will terminate program abnormally

is thrown and caught by the “try” and “catch” keywords correspondingly

Types

unchecked exception

checked exception or unchecked exception

Package

java.lang.Error” package

java.lang.Exception” package

Examples

OutOfMemory, StackOverFlow

  • Checked Exceptions: NoSuchMethod, ClassNotFound
  • Unchecked Exceptions: RuntimeException:
    • NullPointerException
    • IndexOutOfBoundsException
    • ArithmeticException

Checked Exceptions vs Unchecked Exceptions

CHECKED EXCEPTION

UNCHECKED EXCEPTION

Basic

  • the compiler CHECKS the checked exception
  • the compiler does NOT CHECK the unchecked exception

Class of Exception

  • all subclasses of Exception (except RuntimeException)
  • all subclasses RuntimeException
  • all subclasses of Error

Handling

  • compiler REQUIRES developer to handle checked exceptions
  • compiler DOESN’T REQUIRE developer to handle unchecked exceptions

Compilation

  • program doesn’t compile if there is an unhandled checked exception in the program code.
  • program compiles successfully even if there is an unhandled unchecked exception in the program code

Diagram

  • Throwable is the parent class of the classes Error and Exception
  • unchecked exceptions - are the subclasses of RuntimeException and the subclasses of Error
  • checked exceptions - are the remaining subclasses of Exception except RuntimeException