Java try/catch 性能,是否建议将 try 子句中的内容保持在最低限度?
2022-09-01 08:48:09
考虑到你有这样的代码:
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 子句中包含可以实际抛出您正在捕获的异常的行。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;
}
这是考虑到您将以完全相同的方式处理所有这些已检查的异常。