Friday, May 22, 2009

Overriding methods can only throw exception that are thrown by the overridden method

import java.io.IOException;

 

interface TestInterface

{

        void test();

}

 

public class Second implements TestInterface

{

        public void test() throws IOException

        {

                System.out.println("Second.test() invoked");

        }

 

        public static void main(String[] args) throws IOException

        {

                TestInterface j = new Second();

                j.test();

        }

}

 

C:\users\Babu\temp\java>javac Second.java

Second.java:10: test() in Second cannot implement test() in TestInterface; overridden method does not throw java.io.IOException

        public void test() throws IOException

                    ^

1 error

1 comment:

babu said...

The overriding method may choose to NOT throw an exception that is thrown by the overridden method.

E.g.:

interface TestInterface
{
void test() throws IOException;
}

public class Second implements TestInterface
{
public void test()
{
// Overriding method not
// throwing IOException
.. // Perfectly fine.
}
}