Saturday, October 3, 2015

[Java try..finally] Unhandled Exception Type IOException

While trying to program Java Files and I/O on java, I have encountered this error while trying to implement the finally block.

Unhandled Exception Type IOException

This was the code snippet I'd implemented, referred from tutorialspoint's java tutorials:

 
try {
         in = new FileInputStream("input.txt");
         out = new FileOutputStream("output.txt");
         
         int c;
         while ((c = in.read()) != -1) {
            out.write(c);
         }
      }finally {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      }

The trick is to add a catch IOException for the first try and try...catch in the finally block. The fix that works:


try {
 in = new FileInputStream("input.txt");
 out = new FileOutputStream("output.txt");
 while ((c = in.read())!= -1){
 out.write(c);
 }
} catch (IOException e) {
 System.out.println(e);
} finally {
 try {
 if (in != null) in.close();
 if (out != null) out.close(); 
 } catch (IOException ex) {
  System.out.println(ex);
 }
}

That's all for today. Regards, HAJAR.

No comments:

Post a Comment