• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this code is not compiling?

 
Raja seemakurthi
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;
public class Question05 {
public static void main(String[] args) {
Question05Sub myref = new Question05Sub();
try{
myref.test();
}catch(IOException ioe){}
}
void test() throws IOException{
System.out.println("In Question05");
throw new IOException();
}
}
class Question05Sub extends Question05 {
void test() {
System.out.println("In Question05Sub");
}
}
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error message -which you should have posted, by the way, to make it easier for people to help you- is rather specific and to the point, isn't it?

In the future, please UseCodeTags when posting code of any length. It's unnecessarily hard to read as it is, making it less likely that people will do so.
 
avi sinha
Ranch Hand
Posts: 453
Google Web Toolkit Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



making it a bit clear so that i can be able to look into it.
 
avi sinha
Ranch Hand
Posts: 453
Google Web Toolkit Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the catch clause, one can only catch exceptions that are thrown in the corresponding try block. The compiler complains as follows if a catch block exists for an exception that is never thrown in the try block.

the code compiles fine if you change the function test as:

 
avi sinha
Ranch Hand
Posts: 453
Google Web Toolkit Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
overriding methods can throw the same,narrower or no exception as declared to be thrown by the original method.beside it the point is
overriding methods can throw unchecked exception(any nos).
it doesn't matter they are declared by the original method or not.
the reason is that :
compiler doesn't need anything whenever issues related to only unchecked exceptions come up.
the code posted is correct by rules of overriding but compiler is not happy coz it is dealing with IOException.....which is a checked exception.
on compiling the code compiler can't see any stuff related to this exception.


if you will write the same code using unchecked exception compiler will remain happy..

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic