checked exception vs runtimeexception java code example
Example 1: how to know if certain exception is checked or unchecked
1) Look at the hierarchy, if that exception extends RuntimeException then
it is an UNCHECKED exception
if that exception extends Exception, Throwable or
any other Checked Exception, then it is CHECKED exception.
2) Throw it, if it compiles, it is an UNCHECKED exception,
if not it is a CHECKED exception.
throw new SomeException();
Example 2: Unchecked exception
All subclasses of RuntimeException are called unchecked exceptions.
These are unchecked exceptions because compiler does not checks if a method
handles or throws exceptions. Program compiles even if we do not catch the
exception or throws the exception. If an exception occurs in the program,
program terminates. It is difficult to handle these exceptions
because there may be many places causing exceptions.
Example :
1) Arithmetic Exception
2) ArrayIndexOutOfBoundsException
3) ClassCastException
4) IndexOutOfBoundException
5) NullPointerException
6) NumberFormatException
7) StringIndexOutOfBounds
8) UnsupportedOperationException