Java tries and catches IOException problems
I tried to use some of the code I found at the bottom of this page This is the code in the class I created for it:
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    int cnt = 0;
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {}
    cnt = reader.getLineNumber();
    reader.close();
    return cnt;
  }
}
My goal is to calculate the line of the text file, store the number as an integer, and then use the integer in my main class In my main course, I tried several different ways to achieve this, but (as a new programmer) I missed something This is the first thing I tried:
String sFileName = "MyTextFile.txt"; private int lineCount = LineCounter.countLines(sFileName);
Through this attempt, I received the error "unreported exception java.io.ioexception; must be caught or declared to be thrown" I don't understand why I got this because I can see that the exception is declared in my "countlines" method I tried to use the try catch block under the last piece of code I released, but it didn't work (I don't think I did it right) This is what I tried:
String sFileName = "MyTextFile.txt";
private int lineCount;{
    try{
        LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}
Please tell me the way! Thank you for your help!
Solution
The initializer block is like any code bit; It does not "append" to any fields / methods before it To assign a value to a field, you must explicitly use the field as the LHS of the 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);
    }
}
In addition, your countlines can be 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();
  }
According to my test, it seems that you can get linenumber () after close ()
