Java捕获异常和小节 [英] Java catching exceptions and subclases

查看:82
本文介绍了Java捕获异常和小节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

在Java中,如果 BufferedReader.read()之类的方法表示可以抛出 IOException ,我尝试在其中捕获 FileNotFoundException IOException 两个捕获块,如果文件不存在,将输入什么捕获块?

In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?

仅输入最特定的捕获块还是全部输入?

Does it enter only the most specific or both?

推荐答案

将输入与异常匹配的第一个编码捕获。

已编辑包含来自Azodius的注释

The first coded catch that matches the exception will be entered.
Edited to incorporate comment from 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的不可达捕获块。

这篇关于Java捕获异常和小节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆