如何正确处理这个IOException?

问题描述:

public void tokenize(){ 
    // attempt creating a reader for the input 
    reader = this.newReader(); 

    while((line = reader.readLine())!=null){ 
     tokenizer = new StringTokenizer(line); 
     while(tokenizer.hasMoreTokens()){ 
      toke = (tokenizer.nextToken().trim()); 
      this.tokenType(toke); 
      //System.out.println(this.tokenType(toke)); 
     } 

    } 
} 

private BufferedReader newReader(){ 
    try {//attempt to read the file 
     reader = new BufferedReader(new FileReader("Input.txt")); 
    } 

    catch(FileNotFoundException e){ 
     System.out.println("File not found"); 
    } 
    catch(IOException e){ 
     System.out.println("I/O Exception"); 
    } 
    return reader; 
} 

我以为我在newReader()中处理了它,但它似乎无法访问。 Eclipse推荐了一个抛出,但我不明白它在做什么,或者它甚至解决了这个问题?如何正确处理这个IOException?

感谢帮助!

+0

你在说什么IOException,'reader.readLine()'? – home 2012-02-05 17:38:39

如果您不知道如何在此方法中处理IOException,那么这意味着它不是该方法的责任来处理它,因此应该由该方法抛出。

读者应该在此方法中被关闭,不过,因为这种方法打开它:

public void tokenize() throws IOException { 
    BufferedReader reader = null; 
    try { 
     // attempt creating a reader for the input 
     reader = this.newReader(); 
     ... 
    } 
    finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } 
      catch (IOException e) { 
       // nothing to do anymore: ignoring 
      } 
     } 
    } 
} 

另外请注意,除非你的类本身就是一种阅读器的包装另外的读者,因此有着密切的方法,读者不应该是一个实例字段。它应该是一个局部变量,如我的示例中所示。