Exceptions in Java
In Java, there are 3 categories of exceptions:
- Typically a user error
- eg. if a file cannot be found.
- These exceptions cannot simply be ignored at the time of compilation.
runtime exceptions (also called un-checked exceptions)
- exception that could have been avoided by the programmer
- eg. NullPointerException
- ignored at the time of compilation
- These are not exceptions at all
- eg. stack overflow occurs
- 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:
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.