什么时候使用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迷失在其中了。

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

 

posted @ 2014-04-25 12:25  苏大小飞  阅读(1147)  评论(0编辑  收藏  举报