什么时候使用try-catch

上篇文章叙述了try-catch的效率问题,以及StackOverflow上各路大神们指出使用try-catch应该注意的一些问题。


这篇文章作为补充,转述下StackOverflow上各路大神对于何时使用try-catch的一些看法。意见如下:

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

Don't catch an exception if you're only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. 
Even with a checked exception, make sure you log properly and handle as cleanly as possible.

意思就是当且仅当你有一个很重要意义的处理方法来处理这个exception时,才需要使用try-catch。如果仅仅是想要log这个异常信息,还是不必了。


还有人认为我们应该在每一个可能出异常的地方都使用try-catch进行log。


但是很快就有人反驳了他,说是最好的办法是仅仅只在适当的地方进行log,这样系统管理员就不必面对上千记的无意义exception迷失在其中了。


对于这个问题的讨论不是很多,但是绝大多数人都赞同英文部分的观点,所以我们就可以在今后的编程实践中践行这一原则。把我们的代码写得更加科学合理。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值