【发布时间】:2015-11-09 08:30:38
【问题描述】:
我有这个方法应该加载一个文件,但它给了我这个错误:
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();
^
这是我的代码:
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!");
}
}
我很困惑,因为我同时捕获了 IOException 和 FileNotFoundException 但我仍然收到此错误...
【问题讨论】:
-
请遵循正确的命名约定。很难理解您要做什么。
-
尝试将 try-catch 放入
public void run()-method。 -
@UmaKanth 我认为命名约定很好;它恰好是瑞典语。
-
正如@KevinCruijssen 所说。您在
hämtaFrånText()方法中捕获IOException;在run()方法中,抛出该异常的语句所在的位置没有try / catch。 -
我将 try-catch 放在
public void中,但仍然出现错误:NamnMetod.java:157: error: unreported exception InterruptedException; must be caught or declared to be thrown EventQueue.invokeAndWait(new Runnable()
标签: java try-catch bufferedreader