aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Inconsistencies with throwing and catching checked exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Inconsistencies with throwing and catching checked exceptions" Watch "Inconsistencies with throwing and catching checked exceptions" New topic
Author

Inconsistencies with throwing and catching checked exceptions

Andy James
Ranch Hand

Joined: Aug 22, 2005
Posts: 90
In the following code, why does method foo1 compiles, but foo6 fails to compile?



Neither of the relevant code blocks define any code that could potentially throw IOException, in both these methods. So why does only one of them escapes the wrath of the compiler?

Andy
Thorsten Schneider
Greenhorn

Joined: Apr 04, 2011
Posts: 16

Hello Andy,

foo1 compiles, because it's only an information for other code calling foo1, saying that it might(!) throw an exception. You can even decide to handle an Exception inside foo1() and still declare it in the method header.

foo6 won't compile, because IOException is a checked exception, that will never be thrown inside the try-block.


OCPJP 6
Prasanna l reddy
Greenhorn

Joined: Mar 14, 2011
Posts: 12
hello,

Any checked exceptions that are catched in a catch block must thorw in the try block. Otherwise you will get a compiler error. On the other hand you can catch unchecked exception even though you are not throwing in try block. The compiler won't complian.
Compiler error: in order to use chekced exception in catch block that should throw in try block .
void m1() {
try{

}catch(IOException e){

}
}

No compiler error: because it is unchecked exception you are catching:

void m1() {
try{

}catch(ClassCastException e){

}
Babugouda patil
Ranch Hand

Joined: Mar 13, 2011
Posts: 35


Hi Andy,

If your catch block you are catching a checked exception, then there must be possibility of it's occurrence of throwing an exception in try block.

see in your code foo6() method it doesn't throw any related exception so it fail to compile
void foo6 () {
try {}
catch (IOException e) {}
}

if you change this code to like this

Hope you understood this now


SCJP 1.6 91%
Take certification exam as a point of learning not just for certificate
 
Don't get me started about those stupid light bulbs.
 
subject: Inconsistencies with throwing and catching checked exceptions