2017-03-27 32 views
0

我有这个奇怪的行为与try catch块。当我初始化它里面的变量他们似乎是超出范围的,即使我之外声明它们下面的代码..尝试捕获块变量超出范围

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;然后这一切都变好了..不是没有初始化相当于初始化为空的声明..? 摆脱“范围错误”的另一种方式是当我把“返回;”在catch块的末尾..不应该代码运行良好吗?我可以看到这可能会导致错误,但它如何与“fis和fio的范围外错误”相关联?

回答

0

是不是声明没有初始化相当于初始化 为空?

局部变量需要由程序员只,其中的类的实例变量将被JVM的默认值(基于类型)对象创建过程中初始化被初始化。

摆脱“范围错误”的另一种方法是当我把 “返回”; catch块的结束..应该不是代码只是运行 罚款了吗?

有两种可能的位置:

(1)绿色通道情况:如果在第一try块没有FileNotFoundException,然后fis变量会被初始化成功,所以不会有任何错误。

(2)红路径场景:fis不会在第一try块于FileNotFoundException初始化,所以如果从第一catch块本身你return,再有就是在最后try无需fis变量块(因为这些行永远不会执行,因为你从中间返回),所以没有初始化错误。

当我把声明的方法的,让他们静它 也适用..你知道什么是这种区别的原因是什么?

static变量会由JVM默认值(如实例变量)来初始化,因此,如果您将其标记为static(JVM已经没有初始化他们)不会有任何变量初始化错误。

+0

确定我看到..感谢..所以在这种情况下,当我把delarations出来的该方法,并使其静态它也可以工作..你知道这个区别是什么原因吗? – Tummomoxie

+0

更新了答案,你可以看看 – developer

+0

你总是需要初始化你的局部变量 – developer

1

是不是声明没有初始化相当于初始化 为空..?

不在局部变量的情况下。只有实例变量在创建实例时被初始化。

摆脱“范围错误”的另一种方法是当我把 “返回”;

您应该使用try with resources块Java 7中引入它会自动关闭流,如:

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); 
} 
+0

好的感谢提示;) – Tummomoxie