Java 捕获异常和子类
你好,
在 Java 中,如果像 BufferedReader.read()
这样的方法说它可以抛出 IOException
并且我尝试捕获 FileNotFoundException
和 < code>IOException 在两个catch块中,如果文件不存在,会进入什么catch块?
是只输入最具体的还是两者都输入?
Hello,
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将输入与异常匹配的第一个编码捕获。
编辑以纳入 Azodius 的评论
例如:
以下代码无法编译:
编译器消息显示:
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
This following code does not compile:
Compiler message says:
只有遇到的第一个 catch 块(其中 catch 块的异常类型与抛出的异常类型匹配)才会运行(更具体地说,第一个 catch 块,其中
(e instaceof <异常类型>)==true< /code> 将运行)。其他 catch 块都不会运行。
例如
,如果
BufferedReader.read()
抛出FileNotFoundException
,则会打印FileNotFoundException
。请注意,以下内容实际上并未编译:
因为 Java 意识到不可能捕获
FileNotFoundException
,因为所有FileNotFoundException
也是IOExceptions.
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where
(e instaceof <exception type>)==true
will be run). None of the other catch blocks will be run.For example
Will print
FileNotFoundException
ifBufferedReader.read()
throws aFileNotFoundException
.Note that the following doesn't actually compile:
because Java realizes that it is not possible for the
FileNotFoundException
to be caught because allFileNotFoundException
s are alsoIOException
s.第一个适用于该类型的异常(并且仅适用于该异常)。因此,如果您按照列出的顺序
捕获
上面的两种异常类型,则会捕获FileNotFoundException
。The first one which is suitable for that type of exception (and only that). So if you
catch
the two exception types above in the order you list them, aFileNotFoundException
will be caught.首先捕获特定的异常。如果在特定异常之前捕获通用异常,则这是一个编译时错误。
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.