title: Java - Writing a Method to Count Lines In a Text File Without Throwing Exceptions
body: <p>Below is a solution from <a href="https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java">Number of lines in a file in Java</a> 
  to quickly count the number of lines in a text file.</p>
  
  <p>However, I am trying to write a method that will perform the same task <em>without</em> throwing an 'IOException'.</p>
  
  <p>Under the original solution is my attempt to do this with a nested try-catch block &lt;-- (Is this usually done/frowned upon/ or easily avoidable??) which returns 0 no matter how many lines are in the given file (obviously a fail).</p>
  
  <p>Just to be clear, I am not looking for advice on how to better use the original method that does contain the exception and, therefore, the context within which I am using it is irrelevant to this question.</p>
  
  <p>Can somebody please help me write a method that counts the number of lines in a text file and does not throw any exceptions? (In other words, deals with potential errors with a try-catch.)</p>
  
  <p><strong>Original line counter by martinus:</strong></p>
  
  <pre><code>public static int countLines(String filename) throws IOException {
      InputStream is = new BufferedInputStream(new FileInputStream(filename));
      try {
          byte[] c = new byte[1024];
          int count = 0;
          int readChars = 0;
          boolean empty = true;
          while ((readChars = is.read(c)) != -1) {
              empty = false;
              for (int i = 0; i &lt; readChars; ++i) {
                  if (c[i] == '\n') {
                      ++count;
                  }
              }
          }
          return (count == 0 &amp;&amp; !empty) ? 1 : count;
      } finally {
          is.close();
      }
  }
  </code></pre>
  
  <p><strong>My Attempt:</strong></p>
  
  <pre><code>public int countLines(String fileName ) {
     InputStream input = null;
          try{
          try{
              input = new BufferedInputStream(new FileInputStream(fileName));
              byte[] count = new byte[1024];
              int lines = 0;
              int forChar;
              boolean empty = true;
              while((forChar = input.read(count)) != -1){
                  empty = false;
                  for(int x = 0; x &lt; forChar; x++){
                      if(count[x] == '\n'){
                          lines++;
                      }
                  }
              }
              return (!empty &amp;&amp; lines == 0) ?  1 : lines + 1;
          }
          finally{
              if(input != null)
              input.close();
          }
          }
          catch(IOException f){
              int lines = 0;
              return lines;
          }
      }
  </code></pre>