If a method throws NullPointerException in the superclass, can we override it with a method that throws RuntimeException?

Yes, you can override a method in a subclass with a method that throws a different type of exception, even if the superclass method throws a more specific exception. 

In Java, when you override a method, you are allowed to throw a subclass of the exception thrown by the superclass method, or you can choose not to throw any checked exception at all. However, you are not allowed to throw a checked exception that is higher up in the exception hierarchy than the one thrown by the superclass method. In other words, you can only make the exception more specific or leave it unchecked. 

Here's an example to illustrate this:

class Superclass {
    void foo() throws NullPointerException {
        throw new NullPointerException("NullPointerException in Superclass");
    }
}

class Subclass extends Superclass {
    @Override
    void foo() throws RuntimeException {
        throw new RuntimeException("RuntimeException in Subclass");
    }
}

public class Main {
    public static void main(String[] args) {
        Superclass obj = new Subclass();
        obj.foo();
    }
}

Output:

Exception in thread "main" java.lang.RuntimeException: RuntimeException in Subclass
	at Subclass.foo(Main.java:10)
	at Main.main(Main.java:17)

In this example, the Superclass has a method foo() that throws a NullPointerException. The Subclass overrides the method foo() and throws a RuntimeException. This is valid because RuntimeException is an unchecked exception and does not need to be declared in the method signature. 

However, keep in mind that throwing a broader exception in the subclass can lead to a loss of information about the specific exception that occurred in the superclass. So, it's generally considered good practice to maintain the same or more specific exception in the overriding method, and only use unchecked exceptions when necessary.


Comments