本文介绍了(java)从finally {}访问时,try {}中的变量范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到当在try {}中使用以下变量时,我最终无法使用它们的方法,例如:

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

但是如果声明放在main()之前尝试编译没有错误的程序,
有人能指出解决方案/答案/解决方法吗?

But when the declarations where placed in main() before Try{ } the program compiled with no errors,Could someone point me the solution/answer/workaround?

推荐答案

您需要在输入 try 块之前声明变量,以便它们保留在方法的其余部分的范围内:

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

这篇关于(java)从finally {}访问时,try {}中的变量范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:00