Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Never Thrown error

 
Anup Engineer
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I write code in try block that never throws an "Exception" and catch it as catch(Exception e){}
it works. Basically, This works:

import java.io.*;
class NeverThrownException {
public static void main (String[] args) {
try{
return;
}
catch(Exception e){
System.out.println("caught exception");
}
finally{
System.out.println("Finally");
}
} // end of main ()

}

But I have something more specific like IOException instead of Exception it gives me a compile time error:
exception java.io.IOException is never thrown in body of corresponding try statement
catch(IOException e){
this doesnt work:
import java.io.*;
class NeverThrownException {
public static void main (String[] args) {
try{
return;
}
catch(IOException e){
System.out.println("caught IOexception");
}
finally{
System.out.println("Finally");
}
} // end of main ()

}
any ponters?
Thanks.
 
Alex Ku
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I believe it is due to checked/unchecked exception.
And IOException is a checked exception.
If you try ArrayIndexOutOfBoundsException, this compiles fine cuz it is an unchecked exception.
correct me if i am wrong,
kawaii
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We had a discussion on this a while ago:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=015205
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic