问题描述
你能告诉我哪个方法在下面的两个代码块中更好? catch(MyException e){
throw new MyException(Error processing request,e);
}
或
catch(MyException e){
throw e;
}
为了比较两种方法他们应该做同样的事情。这两个,不要做同样的事情。
第一种方法会更好,因为您将其消息更改为更友好的用户。也许你也可以记录它(堆栈跟踪或任何...),然后重新抛出它。
第二种方法对性能更好。实际上,如果你没有抓到这个例外,让它自己也会更好一些。
你必须选择什么是最好的。用户体验,也可能是记录或性能。 默认情况下(而不是总是)我会选择第一个。
希望我帮助!
Could you please tell me which approach is better in below two code blocks?
catch (MyException e) {
throw new MyException ("Error processing request", e);
}
Or
catch (MyException e) {
throw e;
}
In order to compare two approaches, they should do the same thing. These two, do not do the same thing.
The first approach would be better because you would change it's message to a more user friendly one. Perhaps you could also log it (stacktrace or whatever...), before rethrow it.
The second approach is better regarding performance. Actually, it would be even better if you did not catch the exception at all and let it throw it self.
You have to choose what is preferable. User experience and perhaps logging, or performance. By default (and not always) I would choose the first.
Hope I helped!
这篇关于捕捉异常并投掷相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!