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

Douma :

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?

azurefrog :

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

That is the general rule, as specified in the JLS in section §11.2. Compile-Time Checking of Exceptions, which states (emphasis mine)

The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw (§8.4.8.3).

But that only applies to checked exceptions, and it also explicitly states that

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

So the compiler is going to ignore the fact that RuntimeException isn't a subclass of IOException.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322036&siteId=1