Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this compile? Overriding method not a subclass of exception

Tags:

java

exception

I have a hard time to understand why the following code compiles, while it is not a subclass of exception:

class Test 
{
    public void run() throws IOException 
    {
        System.out.println("Test");
    }
}

class SubTest extends Test 
{
    //not a subclass of IOException, still compiles 
    public void run() throws RuntimeException 
    {
        System.out.println("Test from sub");
    }
}

class Sub2Test extends Test 
{
    //not a subclass of IOException, does not compile
    public void run() throws Exception  
    {
        System.out.println("Test from sub");
    }
}

I understand RuntimeException is an unchecked exception, but I thought the rule was that it must be a subclass of the parent exception?

like image 922
Douma Avatar asked Dec 17 '22 15:12

Douma


1 Answers

Imagine there is a caller which calls Test#run. In the declaration of Test#run, it says it might throw IOException, so the caller knows it can catch and handle it:

Test test = // it could be instance of SubTest of Sub2Test
try {
   test.run();
} catch (IOException e) {

}

Then it's ok if SubTest does not throw IOException, the caller will not miss anything.

But if you throw some checked Exception like Sub2Test, since the caller does not know it until runtime, the called is not able to catch and handle it. So it should not be compiled.

like image 56
xingbin Avatar answered Apr 06 '23 00:04

xingbin