2014-04-23 24 views
0

我注意到,當以下變量時嘗試{},我無法使用它們的方法從最後例如:(java)當{finally}從finally {}訪問時try {}中的變量作用域?

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()); 
        } 
      } 
    } 
} 

但是當其中嘗試之前放置在main()聲明{}的程序編譯沒有錯誤, 有人可以指出我的解決方案/答案/解決方法?

+1

'在那裏嘗試之前放置在main()聲明{}這就是解決方案。在更大範圍內聲明變量。 –

+1

沒有解決辦法。這是java中的預期行爲。可變範圍是嚴格的。 – jgitter

+1

如果你在塊內部聲明瞭任何類似'{'或'}'的變量,所以它不能在範圍外訪問。 – iMBMT

回答

1

您需要輸入您的try塊之前聲明變量,使它們保持在範圍爲你的方法的其餘部分:

public static void main() throws FileNotFoundException { 
    File src = null; 
    File des = null; 
    try { 
     src = new File("src.txt"); 
     des = new File("des.txt"); 
     /*code*/ 
    } finally { 
     /*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"); 
     } 
    } 
}