try catch - (java) variable scope inside try { } when accessing from finally { }? -


i noticed when following variables when in try { }, couldn't use methods on them example:

import java.io.*; public class main  {     public static void main()throws filenotfoundexception     {      try{            file src = new file("src.txt");            file des = new file("des.txt");            /*code*/      }      finally{               try{                     /*closing code*/                   system.out.print("after closing files:size of src.txt:"+src.length()+" bytes\t");                   system.out.println("size of des.txt:"+des.length()+" bytes");                   } catch (ioexception io){                        system.out.println("error while closing files:"+io.tostring());                   }             }      } } 

but when declarations placed in main() before try{ } program compiled no errors, point me solution/answer/workaround?

you need declare variables before enter try block, remain in scope rest of method:

public static void main() throws filenotfoundexception {     file src = null;     file des = null;     try {         src = new file("src.txt");         des = new file("des.txt");         /*code*/     } {         /*closing code*/         if (src != null) {             system.out.print("after closing files:size of src.txt:" + src.length() + " bytes\t");         }         if (des != null) {             system.out.println("size of des.txt:" + des.length() + " bytes");         }     } } 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -