1.

What Is The Error In The Following Code?

Answer»

18. class PARENT{
19. PUBLIC void displayMsg() throws IOException{
20. System.out.println("In Parent displayMsg()");
21. throw new IOException("Problem in METHOD - displayMsg - Parent");
22. }
23. }
24. public class ExceptionOverrideDemo extends Parent{
25. public void displayMsg() throws EXCEPTION{
26. System.out.println("In ExceptionOverrideDemo displayMsg()"); 
27. throw new Exception("Problem in method - displayMsg - ExceptionOverrideDemo");
28. }
29. } 

Here parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is WRONG according to the rules of method overriding and exception handling. Thus the code will give compiler error.

18. class Parent{
19. public void displayMsg() throws IOException{
20. System.out.println("In Parent displayMsg()");
21. throw new IOException("Problem in method - displayMsg - Parent");
22. }
23. }
24. public class ExceptionOverrideDemo extends Parent{
25. public void displayMsg() throws Exception{
26. System.out.println("In ExceptionOverrideDemo displayMsg()"); 
27. throw new Exception("Problem in method - displayMsg - ExceptionOverrideDemo");
28. }
29. } 

Here parent class had declared IOException where as subclass has declared Exception. Exception is the super class of IOException thus it is wrong according to the rules of method overriding and exception handling. Thus the code will give compiler error.



Discussion

No Comment Found