Java BufferedReader error with try block

不问归期 提交于 2019-12-24 00:14:58

问题


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...


回答1:


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.
}



回答2:


The try-catch block belongs into the run()-Method of the "Runnable" - this run()-Method must not throw any exception. Submitting the Runnable will not throw exceptions.




回答3:


Below is the solution:

public static void hämtaFrånText() {

        try {
            EventQueue.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    try {
                        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(FileNotFoundException e1) {
                        JOptionPane.showMessageDialog(null,"The file was not found!");
                    }
                    catch(IOException e2) {
                        JOptionPane.showMessageDialog(null, "Failed!");
                    }
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

Reason : run is a method from Runnable and in eventQueue it has been defined and in method definition there is no place where the exception is handled or added in throw in method declaration statement. Hence the FileNoFoundException and IOException both should be given inside the method and not outside.

Also, InterruptedException checked exception was thrown by EventQueue and I added another try catch to handle that exception.

Hope it helps.




回答4:


You need to move your try catch block inside run method, that should do the trick and also you need to handle InvocationTargetException and InterruptedException thrown by EventQueue.invokeAndWait(Runnable) to compile your class properly.




回答5:


You have scope problem here.

The try and catch you are using will catch the exception of hämtaFrånText()But not of the method run()

Exception can happen inside the method run not out side.

The try-Cathc you have given will only care about exceptions that happens in its scope as you haven't throws those exception, it's not your hämtaFrånText() method to take care what happen inside run().

If run was your defined method then you could have throw them. But now only option you have is to catch them inside the run() method.

So try

public void run() {
try{
.............
...........

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


来源:https://stackoverflow.com/questions/33605091/java-bufferedreader-error-with-try-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!