且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java尝试并捕获IOException问题

更新时间:2022-11-15 16:48:48

Initializer块就像任何代码段一样;它没有附加"到它前面的任何字段/方法.要为字段分配值,您必须显式使用字段作为赋值语句的lhs.

Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.

private int lineCount; {
    try{
        lineCount = LineCounter.countLines(sFileName);
        /*^^^^^^^*/
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

此外,您的 countLines 可以变得更简单:

Also, your countLines can be made simpler:

  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    while (reader.readLine() != null) {}
    reader.close();
    return reader.getLineNumber();
  }

根据我的测试,看来您可以在 close()之后 getLineNumber().

Based on my test, it looks like you can getLineNumber() after close().