Java Try and Catch IOException must be caught or declared to be thrown
ioexception, java, try-catch
Solution
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);
}
}
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();
}
Based on my test, it looks like you can `getLineNumber()` after `close()`.
Problem
I am trying to use a bit of code I found at the bottom of this page. Here is the code in a class that 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 objective is to count the lines of a text file, store that number as an integer, then use that integer in my main class. In my main class I tried a few different ways of making this happen, but (being a new programmer) I am missing something. Here is the first thing I tried: ``` String sFileName = "MyTextFile.txt"; private int lineCount = LineCounter.countLines(sFileName); ``` With this attempt I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown." I don't understand why I am getting this because as I can see the exception is declared in my "countLines" method. I tried to use a try catch block right under that last bit of code I posted, but that didn't work either (I don't think I did it right though). Here is my try catch attempt: ``` 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 show me the way!