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

Confused over IOException

Santiago Bravo
Ranch Hand

Joined: Jul 25, 2008
Posts: 226
Hi All,

Im getting a bit confused over IOException. According to the API, IOException is a checked exception.

I thought checked exceptions which occur are picked up at compile-time and runtime exceptions are highlighted at runtime.

So, if I compile the following code with a no-existent file called 'test.txt' the code will compile ok but will give me a checked IOException at runtime.


Please can anyone explain?


===================================================================

import java.io.*;
import java.util.Scanner;

public class myScanTest{
public static void main(String[] args) throws IOException {
Scanner s = null;
try {

s = new Scanner(new BufferedReader(new FileReader("test.txt")));

while (s.hasNext()) {
System.out.println(s.next());

}
}
finally {
if (s != null) {
s.close();
}
}
}
}



===================================================================


Thanks
Quirino Gervacio
Greenhorn

Joined: Aug 09, 2008
Posts: 23
Hi Santiago

FileReader throws a checked exception, the statement is inside try{} so it's OK. But since you provided a fictitious file, a exception is thrown, but based in your code, there is no catch statement for the thrown exception, so JVM will throw it at run time. The finally statement will always run. Add this..
catch(IOException ex){
System.out.println(ex.getMessage());
}

I hope this helps
[ August 09, 2008: Message edited by: Quirino Gervacio ]

SCJP 6.0
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Santiago,

For checked exception, compiler complains you to handle or declare that exception. Code won't get compiled until you do that. Whereas for unchecked exception, compiler does not bother you to handle or declare that exception.


cmbhatt
Clarence J M Tauro
Ranch Hand

Joined: Aug 09, 2008
Posts: 30
Yep..
The compiler does not flag a compiler error.
Checked exception only means, "the compiler ensures that the code giving out a checked exception is put inside a try block or declared as thrown"
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confused over IOException
 
Similar Threads
Scaneer question
Append writeObject()
how to split a text file
IOException
Initialzer's