Exceptions

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
horst1a
Posts: 37
Joined: Mon Jun 12, 2017 2:16 am
Contact:

Exceptions

Post 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 ?

admin
Site Admin
Posts: 10398
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Exceptions

Post 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.

horst1a
Posts: 37
Joined: Mon Jun 12, 2017 2:16 am
Contact:

Re: Exceptions

Post by horst1a »

Thank you !

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 8 guests