如何正确处理此IOException?

时间:2012-02-05 17:29:10

标签: java exception-handling io try-catch

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建议投掷,但我不明白它在做什么,或者它是否甚至解决了问题?

感谢帮助!

1 个答案:

答案 0 :(得分:1)

如果您不知道如何在此方法中处理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
            }
        }
    }
}

另外,请注意,除非您的类本身是一种包含其他阅读器的Reader,因此具有接近的方法,读者不应该是实例字段。它应该是一个局部变量,如我的例子所示。

相关问题