签名声明抛出异常:方法/构造函数不应显式抛出 java.lang.Exception
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14397869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Signature Declare Throws Exception : A method/constructor shouldn't explicitly throw java.lang.Exception
提问by Oomph Fortuity
I got this warning on sonar. what is the proper solution to this warning. My methos is Like:
我在声纳上收到了这个警告。这个警告的正确解决方案是什么。我的方法是:
public void abc(A a) throws Exeption {
dao.pqr(a);
}
i got warning to this method in Class.What is proper solution to this?
我在 Class 中收到了此方法的警告。对此的正确解决方案是什么?
回答by Peter Lawrey
You should throw the actual Exception(s) if they are known.
如果已知,您应该抛出实际的异常。
If the method you call throws Exception
and you can't change it there is nothing you can do about it except suppress the warning.
如果您调用的方法throws Exception
无法更改,则除了取消警告外,您无能为力。
回答by unknown
You can catch the exception and reconvert it to a Particular exception.
您可以捕获异常并将其重新转换为特定异常。
protected RunningJob submitJob(Configuration actionConf) throws RuntimeException {
.....
RunningJob rj;
try{
rj = super.submitJob(actionConf);
}catch(Exception e){
throw new RuntimeException(e);
}
return rj;
}
回答by ThanksForAllTheFish
A method can only throw the exceptions that are relevant to its interface. Exception is the "root" of all exception, so try to be more specific.
一个方法只能抛出与其接口相关的异常。异常是所有异常的“根”,所以尽量具体一些。
回答by Swapnil
If you throw Exception
, it is unclear as which exceptions the method can throw as Exception
is very generic.
如果您 throw Exception
,则不清楚该方法可以抛出哪些异常,因为这Exception
是非常通用的。