Java 7 精确重新抛出和遗留代码
更精确的重新抛出允许编写抛出真正抛出的异常的代码:
public void foo(String bar) throws FirstException, SecondException {
try{
// Code that may throw both FirstException and SecondException
}
catch (Exception e){
throw e;
}
}
在 Java 7 之前,您必须编写:
public void foo(String bar) throws Exception {
try{
// Code that may throw both FirstException and SecondException
}
catch (Exception e){
throw e;
}
}
我的问题:是否有一个工具可以检测不精确的抛出以替换“< code>Exception”与“FirstException,SecondException
”?
到目前为止,我已经检查过Eclipse中没有编译器警告。 FindBugs 或 CodePro 中没有规则。
The more precise rethrow allows to write code that throws the exception really thrown :
public void foo(String bar) throws FirstException, SecondException {
try{
// Code that may throw both FirstException and SecondException
}
catch (Exception e){
throw e;
}
}
Prior to Java 7 you had to write :
public void foo(String bar) throws Exception {
try{
// Code that may throw both FirstException and SecondException
}
catch (Exception e){
throw e;
}
}
My question: is there a tool that allows to detect imprecise throw in order to replace "Exception
" with "FirstException, SecondException
"?
So far, I have checked that there is no compiler warning in Eclipse. There is no rule in FindBugs or CodePro.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这不是编译器警告的情况,因为“过于广泛”的异常不一定是问题:除非该方法是最终的或私有的,否则它定义任何子类实现可以抛出哪种异常。在这种情况下,广泛的范围可能是故意的。
您的问题同样适用于 Java 7 之前的版本:
这里,抛出异常也可能被认为是不好的做法(但没有关于它的警告)。
沿着同一行参数,请注意,当您尝试捕获不可能抛出的(已检查)异常时,您将收到编译错误,但您可以添加到抛出异常方法签名的 code> 子句实现主体未使用的各种异常。
不过像 FindBugs 这样的工具会很有用。
更新:“除非该方法是最终或私有的”:我必须同意,对于私有或最终方法(也可能是静态方法)可能会出现警告。
更新 2:即使对于最终方法,您也可能希望保留选项,以便将来在不破坏接口的情况下抛出更多异常。
I think this is not a situation for a compiler warning, because the "overly broad" exception is not necessarily a problem: Unless the method is final or private, it defines what kind of exception any subclass implementation can throw. In that case, the wide scope may have been intentional.
Your question would apply equally well for Java pre-7:
Here,
throws Exception
could also be considered bad practice (but there are no warnings about it).Along the same line of argument, note that you will get a compile error when you try to catch a (checked) Exception that cannot possibly be thrown, but you can add to the
throws
clause of the method signature all kinds of exceptions that the implementation body does not use.A tool like FindBugs would be useful though.
Update: "Unless the method is final or private" : I have to agree that for private or final methods (and maybe static ones, too) there could be a warning.
Update 2: Even for final methods, you may want to leave your options open to throw more Exceptions in the future without breaking the interface.
尝试在抛出之前强制转换异常,也许可以解决问题?
顺便说一句,重新抛出相同的异常对我来说似乎相当笨拙......
Try casting the exception before throw, maybe it will do the trick?
BTW, rethrowing the same exception seems rather clumsy thing to me...