Exception In java and hierarchy

AI-Native with Idan Gazit


While trying to understand the concept of exception in java , it becomes necessary to understand the hierarchy of exceptions becauce
we can see a famous interview question from exception hierarchy in java developer interview.

suppose we have a parent class with a method that throws IO exception , also there is a sub class that overrides the method of parent class throws FileNotFoundException , will this code works fine or not?

The answer is no because in Java the overridden method in the subclass cannot throw a broader or more general exception than the method in the parent class.

In our scenario IOException is a broader exception than FileNotFoundException, so the overriding method in the subclass is not allowed to throw FileNotFoundException (which is a subclass of IOException) .

let us understand by an example :

We have a parent class

import java.io.FileNotFoundException;
import java.io.IOException;
class ParentClass {
    // Method that throws a narrower exception
    public void Method() throws FileNotFoundException {
        System.out.println("IncorrectParentClass: Method");
        if (true) {
            throw new FileNotFoundException("FileNotFoundException from ParentClass");
        }
    }
}
Enter fullscreen mode

Exit fullscreen mode

Now we are inheriting all the features of super class in our base
class:

 class ChildClass extends ParentClass {
    // Overriding method that throws a broader exception
    @Override
    public void Method() throws IOException {
        System.out.println("IncorrectChildClass: Method");
        if (true) { 
            throw new IOException("IOException from ChildClass");
        }
    }
}
Enter fullscreen mode

Exit fullscreen mode

Now Declaring Main class:

public class Main {
    public static void main(String[] args) {
             ParentClass parent =   new ParentClass();
             ChildClass  child   =  new ChildClass();

        try {
            parent.Method();    
        } catch (FileNotFoundException e) {
            System.out.println("Caught FileNotFoundException from parent: " + e.getMessage());
        }

        try {
            child.Method();
        } catch (IOException e) {
            System.out.println("Caught IOException from child: " + e.getMessage());
        }
    }
}
Enter fullscreen mode

Exit fullscreen mode

When we try to compile Main.java along with ParentClass.java and ChildClass.java, you will get a compilation error indicating that IOException is broader than FileNotFoundException.

The ChildClass will not compile because it violates the rule that an overriding method cannot throw a broader exception than the method it overrides.



Source link
lol

By stp2y

Leave a Reply

Your email address will not be published. Required fields are marked *

No widgets found. Go to Widget page and add the widget in Offcanvas Sidebar Widget Area.