As discussed in User Defined Exception In Java, we can create custom exceptions. But all those exceptions discussed there extended from the class
Exception . Java has one more special class called RuntimeException . We could also extend the custom exceptions from RuntimeException . Any class which extends directly from Exception is called checked exception, where as if it extends from RuntimeException it is called unchecked exception.
The main difference between checked exceptions and unchecked exceptions is, if a method throws a checked exception, then the calling method should have the code to catch it otherwise it will cause compile time error, where as if a method throws an unchecked exception, then it is up to the calling method whether to handle it or not.
class CheckedException extends Exception CheckedException and UncheckedException which extends from Exception and RuntimeException respectively and a class A having two methods method1 and method2 which throw CheckedException and UncheckedException respectively.
If we try to use the method1 which throws a CheckedException , then it has to be handled in a try-catch block, otherwise it causes a compilation error.
void callingMethod1() CheckedException as shown below. So, whoever is calling the callingMethod1 , they have to handle the exception as shown above or indicate to re throw using throws keyword as shown below.
void callingMethod1() throws CheckedException try block and don't throw the exception then it causes a compilation error.
// Causes compilation error. RuntimeException , it is up to the caller whether to catch the exception or not. So all the below 3 cases work with out any error.
void callingMethod2() // Rethrowing the exception is not mandatory void callingMethod2() Also note that the name of sample CheckedException we have used here need not be CheckedException and it could be any thing else like RailwayException or SeatsNotAvailableException, as long as it extends from Exception it is considered checked exception. Similarly the UncheckedException's name need not be that, it could be anything else. As long as any class extends from RuntimeException, then it is considered to be an unchecked exception.
|