gpt4 book ai didi

Java:try-catch错误,必须捕获才能抛出

转载 作者:行者123 更新时间:2023-12-01 06:11:36 25 4
gpt4 key购买 nike

我尝试创建一种加载文件的方法,但它没有按应有的方式工作。为什么我会收到此错误?我的 try-catch block 有问题吗?

NamnMetod.java:157: error: unreported exception InterruptedException; must be caught or declared to be thrown
EventQueue.invokeAndWait(new Runnable() {

这是我的代码:

   public static void hämtaFrånText() {
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,"Filen hittades inte!");
}
catch(IOException e2) {
JOptionPane.showMessageDialog(null,"Det misslyckades");
}
}
});
}

最佳答案

它与run()方法中的try/catch block 无关。问题在于调用 invokeAndWait 的方法... EventQueue.invokeAndWait() 被声明抛出 InterruptedException,这是一个受检查的异常。 .. 因此,要么您需要另一个 try/catch block (在调用周围),要么您的 hämtaFrånText 方法应该声明它也可以抛出 InterruptedException

关于Java:try-catch错误,必须捕获才能抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33606603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com