Page 1 of 1

Exceptions

Posted: Thu Dec 28, 2017 10:18 am
by horst1a
Hello, i have the following code:

Code: Select all

class Foo
{
     void process() throws Exception{
         System.out.println("Foo");
         throw new Exception();
     }
}

class Bar extends Foo{

        void process(){
            System.out.println("Bar");
        }
public static void main(String[] args)
    {
        new Bar().process();
    }
}
why does compiler not complain that i dont treat the exception thrown in class Foo ? Why do i not have to wrap the call to new Bar().process() in a try/Catch block ?

Re: Exceptions

Posted: Thu Dec 28, 2017 3:54 pm
by admin
Remember that compiler takes into account only the type of the reference (and not the type of the actual object pointed to by that reference) to determine whether the method call made using that reference may potentially throw an exception or not. Here the type of reference on which you are invoking process() is Bar. And Bar overrides process() without any throws clause. So the compiler knows that Bar's process does not throw any exception and therefore there is no need for try/catch.

Re: Exceptions

Posted: Fri Dec 29, 2017 7:22 am
by horst1a
Thank you !