aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

kiran goud
Greenhorn

Joined: Apr 21, 2004
Posts: 23
import java.io.*;
class A {

void test() throws IOException {

System.out.println("A");
throw new IOException();

}

public static void main ( String args[] ) {

B b = new B();

try {

b.test();

}

catch ( IOException e ) { System.out.println("kiran"); }


}

}

class B extends A {


void test() {

System.out.println("B");

}

}

When I compile the above program , it will give a compiler error saying
"A.java:24: exception java.io.IOException is never thrown in body of correspondin
g try statement
catch ( IOException e ) { System.out.println("kiran"); }
^
1 error".

But, when i change 'IOException' to 'Exception' it will compile fine.
Could any one tell the logic behind that ??

Thanks in Advance
Kiran
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Look at your definition of B.test() -- it does not declare that it thrown any exceptions. Therefore the compiler won't let you catch anything (insisting that if none are thrown, you shouldn't be attempting to catch anything).

I assume you are getting confused by the fact that your superclass declares that an exception can be thrown. Ignore this though. Function calls are routed polymorphically. If your object is of type B at runtime, B.test will be called, despite what A.test is all about and B extends A. I hope that helps a bit. In short, remove the catch block--it's not necessary.


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
kiran goud
Greenhorn

Joined: Apr 21, 2004
Posts: 23
Hi Nath,

i got that trick .... But My question was when i changed 'IOException' by
'Exception' , it compiled fine. I dont know why it didn't give any error.

Thanks
Kiran
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Sorry about that.

Exception is the superclass of all "checked" and "unchecked" exceptions. As such, you would be able to catch runtime exceptions when you change it from IOException to Exception, e.g. NullPointerException, IndexOutOfBoundsException, etc. You can declare or not declare, but certainly catch, any unchecked exception. Consequently, you can declare to catch any superclass of any unchecked exception. Since Exception is a superclass of unchecked exceptions, this makes it allowable. Tada.
kiran goud
Greenhorn

Joined: Apr 21, 2004
Posts: 23
Got ITTT!!

So, you mean to say that " when there is a catch statement for 'checked exception', it should be reachable. Otherwise it will give compile-time error".


Thanks For your Replies
Kiran
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception