I am beginner with java, please forgive me if I do make any error and suggestion are welcome I would be happy to listen about the errors I made. Thanks In advance for reading and replying to my question.
I get the below code from some book
In the code the new exception is thrown but still the code compiles and one more code similar to that I am pasting but could not understand the different behavior
The first code prints X but according to me the overridden method foo() should not throw new exception. Secondly while calling the method foo, try–catch should be used if a throws clause is there:
class X { public void foo() { System.out.print("X "); } }
public class SubB extends X {
public void foo() throws RuntimeException {
super.foo();
if (true) throw new RuntimeException();
System.out.print("B ");
}
public static void main(String[] args) {
new SubB().foo();
}
}
The second code is similar to above but in this we need to use try–catch while calling the method:
class A {
void foo() throws Exception { throw new Exception(); }
}
class SubB2 extends A {
void foo() { System.out.println("B "); }
}
class Tester {
public static void main(String[] args) {
A a = new SubB2();
a.foo();
}
}
In this exception is extended in the parent class foo method but in the above code the exception is in the subclass’s foo method.
In the first code, you have declared to throw a RuntimeException, which is an
Unchecked Exceptionand does not need to be handled. And hence for this reason, you can also add it in the throws clause of the overriden method, even though it is not in the parent class method.However, in the 2nd code, you have declared to throw
Exceptionwhich is at thetop levelin the Exception hierarchy, and isCheckedby the Compiler and you need to declare in the parent class method throws clause if you are throwing it. Also, you need to handle it too, while invoking the method.Though you cannot increase the restriction in the overriden method in base class, in the sense, you cannot add an extra
Checked Exceptionin the overriden method, however, if you add an UncheckedException, it is allowed.You can go through the following links to know more about
Exception Handling: –