简体   繁体   English

带有try块的Java BufferedReader错误

[英]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...我很困惑,因为我同时捕获了 IOException 和 FileNotFoundException 但我仍然收到此错误...

You are catching them in the code which creates the Runnable , whereas the exceptions need to be caught in Runnable.run() .您在创建Runnable的代码中捕获它们,而需要Runnable.run()捕获异常。

Move the try/catch inside your run method.run方法中移动 try/catch。

Also, use try-with-resources to ensure that the FileReader is always closed, even if an exception occurs:此外,使用 try-with-resources 确保 FileReader 始终关闭,即使发生异常:

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. Reason :run 是 Runnable 中的一个方法,并且在 eventQueue 中它已经定义,并且在方法定义中没有处理异常或在方法声明语句中添加 throw 的地方。 Hence the FileNoFoundException and IOException both should be given inside the method and not outside.因此 FileNoFoundException 和 IOException 都应该在方法内部而不是外部给出。

Also, InterruptedException checked exception was thrown by EventQueue and I added another try catch to handle that exception.此外,EventQueue 抛出了 InterruptedException 检查异常,我添加了另一个 try catch 来处理该异常。

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()您正在使用的 try 和 catch 将捕获hämtaFrånText()的异常,但不会捕获run()方法的异常

Exception can happen inside the method run not out side.异常可以在方法内部发生run不出来的一面。

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() .您提供的 try-Cathc 将只关心在其范围内发生的异常,因为您没有抛出这些异常,而不是您的hämtaFrånText()方法来处理run()内部发生的事情。

If run was your defined method then you could have throw them.如果run是您定义的方法,那么您可以抛出它们。 But now only option you have is to catch them inside the run() method.但现在你唯一的选择是在run()方法中捕获它们。

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. try-catch 块属于“Runnable”的 run()-Method - 这个 run()-Method 不能抛出任何异常。 Submitting the Runnable will not throw exceptions.提交 Runnable 不会抛出异常。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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