Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, October 5, 2015

[Java] Override Error (Java compatibility setting)

I've just learned that there are compatibility settings in Java.

Earlier versions of java doesn't support certain newer features. So whenever you see an error on parts of the code where you really don't see any error, go to project > Properties > Java Compiler > Enable Project specific setting and change the compiler compliance level to a later version, depending on the java features you want to make enabled, such as @Override which only applies to Java 1.5 and up.

Source

Regards,
HAJAR.

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.