aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception problem 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 problem" Watch "Exception problem" New topic
Author

Exception problem

nitude gupta
Ranch Hand

Joined: Sep 04, 2008
Posts: 34
Hello,

while practising on eof the mock from http://www.valoxo.ch/jr/mocks/mock01a.html


import java.io.*;
public class Fundamental15 {
public static void main(String[] args) {
Fundamental15Sub myref = new Fundamental15Sub();
try{
myref.test();
}catch(IOException ioe){}
}
void test() throws IOException{
System.out.println("In Fundamental15");
throw new IOException();
}
}
class Fundamental15Sub extends Fundamental15 {
void test() {
System.out.println("In Fundamental15Sub");
}
}


answer to this is Compiler error!!!

which says

: exception java.io.IOException is never thrown in body of corresponding try statement


Please explain?? why its a compiler error ops:

I think its basic concept regarding exception but unable to figure it!!!

Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Checked exceptions except Exception need to be thrown before catching.


SCJP 6
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

When you write

myref.test();

Type of myred is Fundamental15Sub. So the compiler will look at test method of Fundamental15Sub class which looks like this

void test()

So the compiler knows that it doesn't throw any checked exception. So when you enclose the call into a try catch block and catch IOException which is a checked exception, the compiler will see that the IOException is not thrown by the code in the try block. So it will give a compilation error. As punit said, this is true for all checked exceptions exception Exception and Throwable as they have unchecked sub classes RuntimeException etc...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
nitude gupta
Ranch Hand

Joined: Sep 04, 2008
Posts: 34
Thank you

Both of you Punit and Ankit

your reply was of great help!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exception problem