Exception handling in Method overriding with example


Most interview Question is?Explain Exception Handling in the overriding method?
We all know Overriding. and now we check about exception handling for the overriding method.

Child class method Not sufficient with Parent class method so that is overriding. so here Parent class method is call overridden method or child class method is overriding parent method.

so, overriding method(means child class method) throw any unchecked exception. whether overridden method (means parent class method) throws the exception or not. that can be compilation code successfully.
for example.

class A{
public void color(){
System.out.println("Blue");
}
}
class B extends A{
public void color() throws NullPointerException{
System.out.println("Black");
}
}
public class ExceptionOriding{
public static void main(String args[]){
A a = new B();
ta.color();
}
}

compile successfully. Run successfully.
output : Black

if base class doesn't throw any exception but child class throws a checked exception. then for example:

import java.io.*;
class A{
public void color(){
System.out.println("Blue");
}
}
class B extends A{
public void color() throws IOException{
System.out.println("Black");
}
}
public class ExceptionOriding{
public static void main(String args[]){
A a = new B();
try{
a.color();
}catch(Exception e){
System.out.println(e);
}
}
}
output: ExceptionOriding.java:8: error: color() in B cannot override color() in A
        public void color() throws IOException{
                    ^
  overridden method does not throw IOException
1 error

above,class not run successfully because the overriding method cannot throw a checked exception if the overridden method is not throwing an exception. so we want to need to throw checked exception at overridden method.

import java.io.*;
class A{
public void color()throws IOException{
System.out.println("Blue");
}
}
class B extends A{
public void color() throws IOException{
System.out.println("Black");
}
}
public class ExceptionOriding{
public static void main(String args[]){
A a = new B();
try{
a.color();
}catch(Exception e){
System.out.println(e);
}
}
}
output:Black



Comments