从finally块访问时,try块中的变量作用域是什么? [英] variable scope inside the try block when accessing from the finally block?

查看:92
本文介绍了从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());
                  }
            }
     }
}

但是,如果将声明放置在 try {} 之前的 main()中,则程序编译无误,有人可以给我指出解决方案/答案/解决方法吗?

But when the declarations where placed in main() before the 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");
        }
    }
}

这篇关于从finally块访问时,try块中的变量作用域是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆