你在哪里想赶例外,为什么? [英] Where do you like to catch exceptions and why?

查看:131
本文介绍了你在哪里想赶例外,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你在哪里喜欢捕捉异常,为什么?

Where do you like to catch exceptions and why?

我很感兴趣,看到那里的人们会发现它有用把自己的try / catch块,希望一些通用的模式可能会出现。我会后用C我的两个例子答案++,但任何语言是好的。

I'm interested in seeing where people find it useful to put their try/catch blocks in the hope that some general patterns might emerge. I'll post my two example answers in C++ but any language is fine.

一个位置和每个答案的原因吧。谢谢你。

One location and reason per answer please. Thanks.

推荐答案

不要捕捉任何东西,你是不是要ppared $ P $,并且能够处理。

Don't catch anything that you are not prepared to and able to handle.

所以,的有顶层的异常处理到位轰炸应用你意外的异常喜欢的方式,然后只赶上你需要的东西(如接近的地方,它可能存在的),以获得所需要的功能

So, have top-level exception handling in place to bomb the application the way you like on unexpected exceptions and then only catch the stuff you need (as close to where it might be occuring) to get the functionality that is needed.

和你应该做的只有两件事之一:实际上做一些事情来解决/解决此问题,或者重新抛出具有捕获异常为更具描述性的异常的的InnerException

And you should do only one of two things: actually do something to solve/work around the problem or rethrow a more descriptive exception that has the caught exception as its innerException.

编辑:如果你需要一个最后块(例如,释放你在code分配的东西),你不必做任何有用的东西可能弹出同样的逻辑适用的例外:根本不处理它们。相反,使用抓{抛出; } 将异常重新抛出到更高的水平,同时保持所有的异常信息完好无损。 (或者干脆省略catch块,我想/希望做同样的事情?)

If you need a finally block (e.g. to release something you allocated in your code) and you don't have anything useful to do with any exceptions that might pop up the same logic applies: simply don't handle them. Instead, use a catch { throw; } to rethrow the exception to a higher level while keeping all exception info intact. (Or simply omit the catch block, which I think/hope does the same thing?)

这篇关于你在哪里想赶例外,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆