捕捉异常时为什么订单有问题? [英] Why does order matter when catching exceptions?
问题描述
我必须用一些代码来回答这个问题:
假设我写了以下方法规范:
public void manipulateData()throws java.sql.SQLException,java.sql.SQLDataException
您正在为数据库
程序编写代码,该程序将使用此方法,并且您想要具体处理每个
。 try / catch子句应该是什么样的?
您可以对catch子句内容使用no-ops--空块{} -
我们只对这里的语句的语法和结构感兴趣。
我回答了这个:
$ b $ (b catch(java.sql.SQLDataException e){
}
他没有接受这个理由的答案:
你的catch子句的顺序是错误的,你能解释为什么这个顺序很重要吗?
他的答案是否正确?
是的,他是正确的。您可以在 Javadoc 中看到, SQLDataException
是 SQLException
的子类。因此,您的答案是错误的,因为它会在第二个 catch
中创建一个无法访问的代码块。
在Java中,此代码甚至无法编译。在其他语言(例如python)中,这样的代码会创建一个微妙的错误,因为 SQLDataException
实际上会被捕获在第一个块中,而不是在第二个块如果它不是一个子类的话)。
如果您回答了 catch(java.sql.SQLException | java.sql.SQLDataException e){}
,那么仍然是不正确的,因为问题要特别处理每个异常。
正确的答案是 Grijesh的答案
I had to answer this question with some code:
Suppose I wrote the following method specification:
public void manipulateData ( ) throws java.sql.SQLException, java.sql.SQLDataException
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.
I answered with this:
try {
} catch(java.sql.SQLException e) {
}
catch(java.sql.SQLDataException e) {
}
He did not accept the answer for this reason:
"Your catch clauses are in the wrong order. Can you explain why the order matters?"
Is he correct in his answer?
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
.
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).
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.
The correct answer is in Grijesh's answer
这篇关于捕捉异常时为什么订单有问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!