java try 性能损耗_Java try/catch性能,建议尽量减少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.

现在我知道了,在构造异常时,实际上存在性能问题,特别是在展开堆栈时。我也读过几篇文章,指出在进入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;

}

这是在考虑您将以完全相同的方式处理所有这些选中的异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值