Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1097 :
Posted: Sat Jul 27, 2013 4:13 pm
by CreepyMulder
Hello o/,
Why isn't there any compilation issue as Exception is never thrown in the Try block? Is it because somewhere in the System.out.println method there can be an Exception thrown?
If I modify the code like that :
Code: Select all
try{
amethod();
System.out.println("try");
}
catch(FileNotFoundException e){
System.out.println("catch");
}
finally {
System.out.println("finally");
}
System.out.println("out");
It does not compile as "FileNotFoundException" is never throw. How do the compiler can figure that FileNotFoundException is never thrown, but doesn't complain about "Exception" ?
Thank you

Re: About Question enthuware.ocajp.i.v7.2.1097 :
Posted: Sun Jul 28, 2013 8:17 am
by admin
Very good question.
The issue is that RuntimeException is a subclass of Exception and any exception that extends RuntimeException need not be declared in the throws clause. Because of this reason, when you have catch(Exception e), the compiler can never tell whether the code in try catch will not throw any exception (because it is always a possibility that a RuntimeException, which is-a Exception may be thrown). So it has to allow the catch(Exception e) part.
However, with any other checked exception such as FileNotFoundException, compiler can easily determine if this exception is never thrown. Because if it is thrown, it would be present in the throws clause of the method. Thus, if it sees that there is no method call in the try block that has "throws FileNotFoundException", it can generate an error saying this exception is never thrown.
HTH,
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1097 :
Posted: Sun Jul 28, 2013 8:39 am
by CreepyMulder
Thanks ! It make more sense now

Re: About Question enthuware.ocajp.i.v7.2.1097 :
Posted: Wed Oct 15, 2014 5:49 am
by chipchipchonkeykonky
very good test question

Re: About Question enthuware.ocajp.i.v7.2.1097 :
Posted: Thu Mar 30, 2017 4:27 am
by mjmsausava
In case of the modified code above (copied below):
Code: Select all
try{
amethod();
System.out.println("try");
}
catch(FileNotFoundException e){
System.out.println("catch");
}
finally {
System.out.println("finally");
}
System.out.println("out");
the amethod() will declare the exception in its signature because its specifically modified to a check exception here . Right?
Re: About Question enthuware.ocajp.i.v7.2.1097 :
Posted: Thu Mar 30, 2017 4:56 am
by admin
I am sorry but I am not sure I understand your question. Please post the complete code that you have tried compiling and executing.
Paul.