Let us take an interview Question.
There is a method that throws NullPointerException in the superclass. Can we override it with a
method that throws RuntimeException?
To answer this question, let us know what is an Unchecked and Checked exception.
Checked exceptions must be explicitly caught or propagated as described in
Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement.
They don't have to be caught or declared thrown.
Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.
public class NullPointerException extends RuntimeException
Unchecked exceptions extend the java.lang.RuntimeException.
Thst's why NullPointerException is an Uncheked exception.
Let's take an example:
Example 1 :
public class Parent {
public void name() throws NullPointerException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws RuntimeException{
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.name();// output => child
}
}
The program will compile successfully.
Example 2:
public class Parent {
public void name() throws RuntimeException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws NullPointerException {
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.name();// output => child
}
}
The program will also compile successfully.
Therefore it is evident, that nothing happens in case of Unchecked exceptions.
Now, let's take a look what happens in case of Checked exceptions.
Example 3:
When base class and child class both throws a checked exception
public class Parent {
public void name() throws IOException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws IOException{
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.name();// output=> child
}catch( Exception e) {
System.out.println(e);
}
}
}
The program will compile successfully.
Example 4:
When child class method is throwing border checked exception compared to the same method of base class.
import java.io.IOException;
public class Parent {
public void name() throws IOException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws Exception{ // broader exception
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.name();//output=> Compilation failure
}catch( Exception e) {
System.out.println(e);
}
}
}
The program will fail to compile. So, we have to be careful when we are using Checked exceptions.