简体   繁体   中英

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

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

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.

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!");
    }
}

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.

您需要在 run 方法中移动 try catch 块,这应该可以解决问题,并且您还需要处理EventQueue.invokeAndWait(Runnable)抛出的InvocationTargetExceptionInterruptedException以正确编译您的类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM