views:

29

answers:

2

Hi, I was expecting an compilation error in the following program because of the throw statement in the catch block as IOException is a checked exception and it is not caught by another try block within the catch block. But I am getting "Hurray!" printed. Any explanation would be much appreciated.

According to JLS 11.2.3, http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html

It is a compile-time error if a method or constructor body can throw some exception type E when both of the following hold:

* E is a checked exception type
* E is not a subtype of some type declared in the throws clause of the

method or constructor.

import java.io.*;
public class Test{ 
    public static void main(String args[])
    {


        System.out.println(method()); 
    } 
    public static int method()
    {


        try{ 
            throw new Exception(); 
        }
        catch(Exception e){

            throw new IOException(); //No compile time error
        } 
        finally{

                    System.out.println("Hurray!");

        } 
    }
}

Thanks in advance.

A: 

That gives a compilation error using Eclipse's built-in Java compiler.

Same for the JDK 6.0 compiler.

What version of Java are you using that gives no compilation error?

Stephen C
Strange! I am using eclipse galileo too. No compilation error here.
srandpersonia
I am using jdk 6 update 14.
srandpersonia
Phew! Got it now after creating a new class file and copy pasting from SO. I assume that it should have been because I was using using Exception before changing that to IOException and an automatic build was not taking place. Thanks for your reply and time.
srandpersonia
A: 

Maybe I'm missing something, but where is the throws clause in your program?

The source code as it appears now for method() does not contain a throws clause at the method header, just throw statements. Your quote from the JLS explicitly refers to throws clause.

Uri
As I commented on the other reply, It was a mistake on my part not forcing the build. Sorry, thanks for your time.
srandpersonia