java - 尝试 catch block 变量超出范围

标签 java scope null return try-catch

我对 try catch block 有这种奇怪的行为。当我初始化其中的变量时,即使我在外部声明它们,它们似乎超出了以下代码的范围..

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;



public class CopyFile {
    public static void main(String[] args) {
        FileInputStream fis;
        FileOutputStream fos;
        args[0] = "somefile.txt";
        args[1] = "copyithere.txt";
        int i;

        try {
            try {
                fis = new FileInputStream(args[0]);
            } catch (FileNotFoundException e) {
                System.out.println("Input file not found");
                e.getMessage();
            }
            try {
                fos = new FileOutputStream(args[1]);
            } catch (FileNotFoundException e) {
                System.out.println("Output file not found");
                e.printStackTrace();

            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Give input and output file name");
            e.getStackTrace();

        }
        try {
            do {
                i = fis.read();
                fos.write(i);
            } while (i != -1);

        } catch (IOException e) {
            System.out.println("Some IO exception");
            e.getMessage();
        }

    }
}

奇怪的是,当我将变量声明为 null 时“FileInputStream fis = null; 然后一切都会好起来.. 没有初始化的声明不等于初始化为 null..? 摆脱“超出范围错误”的另一种方法是当我输入“return;”时在 catch block 的末尾......代码不应该在没有它的情况下正常运行吗?我可以看到这可能会导致错误,但这与“fis 和 fio 超出范围错误”有何联系?

最佳答案

isn't declaration without initialization equivalent to initialization to null..?

不适用于局部变量。创建实例时仅初始化实例变量。

The other way which gets rid off "out of scope error" is when I put "return;"

您应该使用 Java 7 中引入的 try with resources block 。它将自动关闭流,例如:

int i;
try(FileInputStream fis = new FileInputStream(args[0]);
        FileOutputStream fos = new FileOutputStream(args[1]);){
    do {
        i = fis.read();
        fos.write(i);
    } while (i != -1);
}

关于java - 尝试 catch block 变量超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057248/

相关文章:

c - 编译器如何区分名称相同的项目

c++ - 我是否需要 "new"数组以便稍后执行 memset?在 C++ 中

C++ 类变量作用域

c# - 值不能为空。参数名称: entity

java - JTable:如何将 boolean 值呈现为颜色,并使用 JTextField 编辑为文本?

java - 在 Redis 重启时自动将 Storm Topology 重新连接到 Redis Cluster

C#:对象变量应该赋值给 null 吗?

如果没有找到结果,SQL 返回行

java - 应该 FileOutputStream.close();在 IOException 的 catch block 中调用?

java - Maven 配置文件 - 无需子项目即可构建