【问题标题】:variable scope inside the try block when accessing from the finally block?从finally块访问时try块内的变量范围?
【发布时间】:2014-04-23 16:14:42
【问题描述】:

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

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()之前放在try{}之前,程序编译没有错误, 有人可以指出我的解决方案/答案/解决方法吗?

【问题讨论】:

  • when the declarations where placed in main() before Try{ } 这就是解决方案。在更大的范围内声明变量。
  • 没有变通办法。这是 java 中的预期行为。变量范围很严格。
  • 如果您在块内声明了任何变量,例如{},那么它就无法在作用域外访问。

标签: java try-catch block scope finally


【解决方案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");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2011-02-20
    • 2017-07-20
    • 2014-01-08
    相关资源
    最近更新 更多