Woodstock Blog

a tech blog for general algorithmic interview questions

[Java OOP] Java Runtime Exception

Exceptions in Java

In Java, there are 3 categories of exceptions:

  1. checked exceptions

    1. Typically a user error
    2. eg. if a file cannot be found.
    3. These exceptions cannot simply be ignored at the time of compilation.
  2. runtime exceptions (also called un-checked exceptions)

    1. exception that could have been avoided by the programmer
    2. eg. NullPointerException
    3. ignored at the time of compilation
  3. error

    1. These are not exceptions at all
    2. eg. stack overflow occurs
    3. also ignored at the time of compilation

1. checked exception

A checked exception must be handled explicitly by the code (by either putting a try/catch block around the code, or adding a “throws” clause to the method).

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Example:

  1. FileNotFoundException
  2. HttpRetryException
  3. SocketException
  4. IOException

Note: java.lang.RuntimeException is a subclass of java.lang.Exception.

2. un-checked exceptions (RuntimeException)

A un-checked exception does not need to be explicitly handled.

RuntimeException and its subclasses are unchecked exceptions.

Generally RuntimeExceptions can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.

The runtime exception classes are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur.