1

我的代码看起来像:

public static void func(Reader r){
    int c = r.read();
    ...
}

编译器告诉我这r.read()可能会抛出一个IOException. 在什么情况下会发生这种情况?似乎很清楚,FileNotFoundException当找不到文件时会抛出类似的东西,但是IOException相当模糊。

编辑:

如果有人对此感兴趣,我问了这个问题,因为我认为必须有更好的方法来处理这种情况,而不仅仅是printStackTrace. 但是,在不知道可能导致异常的原因的情况下,我不确定应该如何完成。

4

6 回答 6

1

很多事情都可能导致 IOException。当它被抛出时,您可以将其打印出来或检查消息 ( Exception.getMessage()) 以查看导致它的原因。

AFileNotFoundException是 的一个子类IOException,你可以查看其他的“已知子类”列表

于 2012-07-04T06:43:57.247 回答
1

IOException当流本身损坏或在读取数据期间发生某些错误时,它可能会抛出一个错误,即安全异常、权限被拒绝等和/或一组衍生自 的异常IOEXception

于 2012-07-04T06:45:11.587 回答
1

例如:

public void load(InputStream inputStream) throws IOException {
    this.inputStream = inputStream;
    this.properties.load(this.inputStream);
    this.keys = this.properties.propertyNames();
    inputStream.close();
}

我认为那是由于安全性或例如未打开流而导致输入/输出(连接)出现问题的时候。

代码来源:stackoverflow

于 2012-07-04T06:51:11.467 回答
0

IOException 是 CharConversionException、CharacterCodingException 和 EOFException 等许多异常的超类。

如果该方法列出了所有这些异常,那么调用者必须捕获所有这些异常。因此,为了方便起见,在 throws 子句中使用 IOException 有助于调用者避免多个 catch 块。如果他们愿意,用户仍然可以通过检查实例或 exception.getMessage() 来处理特定的异常。

于 2012-07-04T06:46:40.123 回答
0

如果您想了解具体信息,请在您的 catch 块中执行以下操作:

catch (IOException e)
{
    e.printStackTrace();
}
于 2012-07-04T06:47:06.997 回答
0

此代码将帮助您调试并查看抛出的 IOException:

String NL = System.getProperty("line.separator");
String line;
FileInputStream in;
try {
      fileName = choose.getSelectedFile().getCanonicalPath();
} catch (IOException e) {
      e.printStackTrace();  //This doesn't matter, see the second IOException catch.
}

try {
in = new FileInputStream(choose.getSelectedFile());
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer content=new StringBuffer("");

while((line = reader.readLine()) != null){
    content.append(line+NL);
}

    textArea.setText(content.toString());
    reader.close();
    reader.readLine();

} catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(new JFrame(), "The file does not exist!", "Error", JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
            JOptionPane.showMessageDialog(new JFrame(), "There was an error in reading the file.", "Error", JOptionPane.WARNING_MESSAGE);
}

祝你好运。

于 2013-01-02T09:05:40.913 回答