What will be the result after compiling this code?
class SuperClass{
public int doIt(String str, Integer... data)throws Exception{
String signature = "(String, Integer[])";
System.out.println(str + " " + signature);
return 1;
}
}
public class Test extends SuperClass{
public int doIt(String str, Integer... data){
String signature = "(String, Integer[])";
System.out.println("Overridden: " + str + " " +signature);
return 0;
}
public static void main(String... args){
SuperClass sb = new Test();
sb.doIt("hello", 3);
}
}
class SuperClass{
public int doIt(String str, Integer... data)throws Exception{
String signature = "(String, Integer[])";
System.out.println(str + " " + signature);
return 1;
}
}
public class Test extends SuperClass{
public int doIt(String str, Integer... data){
String signature = "(String, Integer[])";
System.out.println("Overridden: " + str + " " +signature);
return 0;
}
public static void main(String... args){
SuperClass sb = new Test();
sb.doIt("hello", 3);
}
}
A. Overridden: hello (String, Integer[])
B. hello (String, Integer[])
C. Compilation fails
D. None of these
Answer: Option C
Solution(By Examveda Team)
Exception must be caught or declared to be thrown.
doIt() method of SuperClass throws an Exception but does not catch or declare's the exception.
Rule: If you are calling a method that declares an exception, you must either caught or declare the exception.
There are two cases:
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
What exception is occurring here?
Why here Exception must be caught or declared to be thrown ?