你喜欢在哪里捕捉异常,为什么? [英] Where do you like to catch exceptions and why?

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

问题描述

您喜欢在哪里捕获异常以及为什么?

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.

推荐答案

不要抓住任何你没有准备好也没有能力处理的东西.

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.

如果你需要一个 finally 块(例如释放你在你的代码中分配的东西)并且你没有任何有用的东西来处理任何可能弹出的异常,同样的逻辑适用: 干脆别管它们.相反,使用 catch { throw;} 将异常重新抛出到更高级别,同时保持所有异常信息完整.(或者干脆省略 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天全站免登陆