当我调用 Reader.read() 时,什么可能会导致 Java 中的 IOException



我的代码看起来像:

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

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

编辑:

如果有人感兴趣,我问这个问题是因为我认为一定有比printStackTrace更好的处理情况的方法。但是,由于不知道可能导致异常的原因,我真的不确定应该如何完成。

很多事情都可能导致 IOException。当它被抛出时,你可以把它打印出来或检查消息(Exception.getMessage())看看是什么导致了它。

FileNotFoundExceptionIOException的子类,可以查看其他子类的"已知子类"列表。

例如:

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

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

代码源:堆栈溢出

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

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

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

如果你想知道细节,在你的 catch 块中这样做:

catch (IOException e)
{
    e.printStackTrace();
}

此代码将帮助您调试并查看抛出的 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);
}

祝你好运。

相关内容

最新更新