[英]Java catching exceptions and subclases
你好,
在 Java 中,如果像BufferedReader.read()
这样的方法说它可以抛出IOException
并且我尝试在两个 catch 块中捕获FileNotFoundException
和IOException
,如果文件不存在,将输入什么 catch 块?
它是只输入最具体的还是两者都输入?
将输入与异常匹配的第一个编码捕获。
编辑以纳入 Azodius 的评论
例如:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
以下代码无法编译:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
编译器消息说:
FileNotFoundException 的无法到达的 catch 块。 它已经由 IOException 的 catch 块处理
只有遇到的第一个 catch 块的异常类型与抛出的异常类型匹配时才会运行(更具体地说,将运行(e instaceof <exception type>)==true
的第一个 catch 块)。 不会运行任何其他 catch 块。
例如
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
如果BufferedReader.read()
抛出FileNotFoundException
FileNotFoundException
请注意,以下内容实际上并未编译:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
因为 Java 意识到不可能捕获FileNotFoundException
因为所有FileNotFoundException
也是IOException
。
第一个适用于该类型的异常(并且仅适用于该异常)。 因此,如果您按照列出的顺序catch
上述两种异常类型,则会捕获FileNotFoundException
。
首先捕获特定异常。 如果在特定异常之前捕获到通用异常,则这是编译时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.