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

久未见 提交于 2019-12-20 05:21:26

问题


I noticed that when the following variables when in try { }, I couldn't use methods on them from finally for 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 the declarations where placed in main() before Try{ } the program compiled with no errors, Could someone point me the solution/answer/workaround?


回答1:


You need to declare your variables before you enter your try block, so that they remain in scope for the rest of your 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*/
    } 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");
        }
    }
}


来源:https://stackoverflow.com/questions/23249951/java-variable-scope-inside-try-when-accessing-from-finally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!