为什么在捕获异常时顺序很重要? [英] Why does order matter when catching exceptions?
问题描述
我不得不用一些代码来回答这个问题:
I had to answer this question with some code:
假设我编写了以下方法规范:public void handleData() 抛出 java.sql.SQLException, java.sql.SQLDataException
Suppose I wrote the following method specification:
public void manipulateData ( ) throws java.sql.SQLException, java.sql.SQLDataException
您正在为数据库编写代码将使用此方法的程序并且您想要处理每个具体来说.try/catch 子句应该是什么样的?
您可以使用 no-ops-- empty blocks {}--作为 catch 子句的内容.
我们只对这里的语句的语法和结构感兴趣.
You are writing code for a database
program that will use this method and you want to handle each
specifically. What should the try/catch clause look like?
You can use no-ops-- empty blocks {}--for the catch clause contents.
We are only interested in the syntax and structure of the statements here.
我是这样回答的:
try {
} catch(java.sql.SQLException e) {
}
catch(java.sql.SQLDataException e) {
}
他没有接受这个原因的答案:
He did not accept the answer for this reason:
您的 catch 子句顺序错误.您能解释一下为什么顺序很重要吗?"
"Your catch clauses are in the wrong order. Can you explain why the order matters?"
他的回答正确吗?
推荐答案
是的,他是对的.正如您在 Javadoc 中所见,SQLDataException
是 SQLException
的子类.因此,您的答案是错误的,因为它会在第二个 catch
中创建一个无法访问的代码块.
Yes he is correct. As you can see in the Javadoc, SQLDataException
is a subclass of SQLException
. Therefore, your answer is wrong, since it would create a block of unreachable code in the second catch
.
在 Java 中,此代码甚至无法编译.在其他语言(例如 python)中,这样的代码会产生一个微妙的错误,因为 SQLDataException
实际上会在第一个块中被捕获,而不是在第二个块中(如果它不是一个子类).
In Java, this code would not even compile. In other languages (e.g. python) such code would create a subtle bug, because SQLDataException
would actually be caught in the first block, and not in the second one (as would be the case if it was not a subclass).
如果您回答了 catch(java.sql.SQLException | java.sql.SQLDataException e) { }
,它仍然是不正确的,因为该问题要求专门处理每个异常.
Had you answered catch(java.sql.SQLException | java.sql.SQLDataException e) { }
, it would still be incorrect, since the question asks to handle each exception specifically.
正确答案在 Grijesh 的答案
这篇关于为什么在捕获异常时顺序很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!