views:

77

answers:

4

I have an Exception chain in which method1 throws an Exception to method2 which throws the Exception on to main. For some reason, the compiler forces me to deal with the error in method2 and marks it as an error if I don't, indicating that it's a checked Exception. But when the same Exception is thrown further down the line to main, the compiler allows me to ignore it and doesn't display any errors.

The original Exception in method1 is a ParseException, which is checked. But the method has a generic throws Exception clause in the header, and the same object is thrown to method2, which has an identical throws Exception clause. When and how does this Exception lose the status of being checked / caught by the compiler?

Edited to clarify:

public void method1() throws Exception{
   // code that may generate ParseException
}

public void method2() throws Exception{
   method1(); //compiler error (if the throws clause is left out)
}

public static void main(String[] args){
   method2(); //ignored by compiler, even though the exception isn't caught or thrown or handled at all
}

Edit: Sorry everyone, the question was based on a mistake... The main method actually had a throws Exception clause that I was missing. I've removed that and the code is now behaving as expected. Thanks for all the help!

+3  A: 

A checked exception does not stop being a checked exception. The way you can sort of turn a checked exception into unchecked is by wrapping it inside a type of RuntimeException and re-throwing it.

Jarle Hansen
+5  A: 
T.J. Crowder
So why is main fine with no handling, while method2 requires it to be dealt with?
froadie
@froadie: It isn't, that code won't compile.
T.J. Crowder
oops! I just realized my mistake. There was actually a `throws Exception` clause in main's header... When I take that out the compiler errors I was expecting show up. Sorry about that, thanks for your help!
froadie
+2  A: 

In your case, it'll be Exceptions all the way down to the root of the call stack. If a method is declared to throw Exception (which methods very seldom should do), the calling method will either have to say it throws Exception too, or catch it and deal with it.

Edit As for the example in the edited OP, that won't compile. You can declare main to throw Exception if you don't want to deal with it, though.

gustafc
A: 

Is it possible that your compiler is not complaining about the issue in main() because it hits the issue in method2() and stops checking the syntax at that point? Both should be an error. Have you fixed the call in method2() and gotten a clean compile?

justkt