【问题标题】:How to correctly handle this IOException?如何正确处理这个 IOException?
【发布时间】:2012-02-27 09:48:55
【问题描述】:
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 建议使用 throws,但我不明白它在做什么,或者它是否解决了问题?

感谢您的帮助!

【问题讨论】:

  • 你说的是哪个 IOException,reader.readLine()?

标签: java exception-handling io try-catch


【解决方案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
            }
        }
    }
}

另外,请注意,除非您的类本身是一种包装另一个阅读器的阅读器,因此具有关闭方法,否则阅读器不应是实例字段。它应该是一个局部变量,如我的示例所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2013-11-11
    • 1970-01-01
    相关资源
    最近更新 更多