考虑到你有这样的代码:
doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
现在我知道了,在构造异常时,实际上存在性能问题,特别是在展开堆栈时。我也读过几篇文章,指出在进入try/catch块时性能会受到轻微影响,但这些文章似乎都没有任何结论。
我的问题是,是否建议尽量减少try catch中的行数?,也就是说,只有在try子句中有可以实际抛出您捕获的异常的行try子句中的代码运行速度慢还是导致性能下降?.
但更重要的是,考虑到这样做,什么是最佳实践/更具可读性的解决方案:
try {
doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
}
catch (MyCheckedException e) {
//handle it
}
或:
try {
doSomething() // this method may throw a checked a exception
}
catch (MyCheckedException e) {
//Store my exception in a Map (this is all running in a loop and I want it to continue running, but I also want to know which loops didn't complete and why)
continue;
}
//do some assignements calculations
try {
doAnotherThing() // this method may throw a checked a exception
}
catch (MyCheckedException e) {
//Store my exception in a Map (this is all running in a loop and I want it to continue running, but I also want to know which loops didn't complete and why)
continue;
}
这是在考虑您将以完全相同的方式处理所有这些选中的异常。