(java)从finally {}访问时,try {}中的变量范围?

时间:2014-04-23 16:14:42

标签: java try-catch block scope 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());
                  }
            }
     }
}

但是当在try {}之前放置在main()的声明时,编译的程序没有错误, 有人能指出解决方案/答案/解决方法吗?

1 个答案:

答案 0 :(得分: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");
        }
    }
}