Java捕获异常和子类

Fra*_*fka 2 java exception-handling exception try-catch throw

你好,

在Java中如果一个方法BufferedReader.read()说它可以抛出一个IOException并且我尝试捕获一个FileNotFoundException和一个IOException两个catch块,如果该文件不存在,将输入什么catch块?

它只输入最具体的或两者兼而有之吗?

Boh*_*ian 6

将输入匹配异常的第一个编码catch.
编辑纳入Azodius的评论

例如:

try {
   bufferedReader.read();
} catch (FileNotFoundException e) {
   // FileNotFoundException handled here
} catch (IOException e) {
   // Other IOExceptions handled here
}
Run Code Online (Sandbox Code Playgroud)

以下代码无法编译:

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
}
Run Code Online (Sandbox Code Playgroud)

编译器消息说:

FileNotFoundException的无法访问的catch块.它已由catch块处理IOException