File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inconsistencies with throwing and catching checked exceptions

 
Andy James
Ranch Hand
Posts: 90
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
Eclipse IDE Firefox Browser Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Prasanna l reddy
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 35
Eclipse IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic