Search code examples
javatry-catchbufferedreader

Java BufferedReader error with try block


I have this method that is supposed to load a file but it is giving me this error:

NamnMetod.java:175: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
                 BufferedReader inFil = new BufferedReader(new FileReader(fil));
                                                           ^
NamnMetod.java:177: error: unreported exception IOException; must be    caught or declared to be thrown
                 String rad = inFil.readLine();  
                                            ^

This is my code:

   public static void hämtaFrånText() {
    try {
     EventQueue.invokeAndWait(new Runnable() {
     @Override

        public void run() {
              String aktuellMapp = System.getProperty("user.dir");
           JFileChooser fc = new JFileChooser(aktuellMapp);
           int resultat = fc.showOpenDialog(null);

              if (resultat != JFileChooser.APPROVE_OPTION) {
                 JOptionPane.showMessageDialog(null, "Ingen fil valdes!");
                 System.exit(0);
              }
                 String fil = fc.getSelectedFile().getAbsolutePath();
                 String[] namn = new String[3];         
                 String output ="";         
                 BufferedReader inFil = new BufferedReader(new FileReader(fil));                    
                 String rad = inFil.readLine();

                 int antal = 0;

                    while(rad != null){                  
                        namn[antal] = rad;
                        rad = inFil.readLine();
                        antal++;
                    }
                    inFil.close();

       }
    });                     
    }catch(IOException e2) {        
        JOptionPane.showMessageDialog(null,"The file was not found!");
    }           
}

I'm perplexed because i have caught both IOException and FileNotFoundException but I still get this error...


Solution

  • You are catching them in the code which creates the Runnable, whereas the exceptions need to be caught in Runnable.run().

    Move the try/catch inside your run method.

    Also, use try-with-resources to ensure that the FileReader is always closed, even if an exception occurs:

    try (FileReader fr = new FileReader(fil);
         BufferedReader inFil = new BufferedReader(fr)) {
      // ...
    
      // No need to close `fr` or `inFil` explicitly.
    }