您将C ++异常用于什么? [英] What do You Use C++ Exceptions For?

查看:102
本文介绍了您将C ++异常用于什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是最有争议的C ++功能。许多团队包括Google 都不使用它们。当然,是否使用它们的决定取决于上下文-例如,在某些游戏中,可以在内存不足时崩溃,但在医疗设备控制软件中则不会崩溃。除了内存不足之外,有些团队可能会使用异常来破坏网络,找不到文件等。但是其他团队可能会说这种情况太普遍了,因此不能称之为异常(其他人可能会说,但是如果很常见,那么该怎么办? ?)

Probably exceptions is the most controversial C++ feature. Many teams including google do not use them. Of course the decision to use them or not depends on the context -- for example, in some games it might be ok to crash on out-of-memory, but not in a medical equipment control software. Apart from out-of-memory, some teams may use exceptions for network disruption, file-not-found etc. but others may say this is too common to be called an exception (others may say, but if it is common, so what?)

通常,不使用异常的决定是基于潜在的误导性论点,即难以编写异常安全代码。有人说该参数是错误的,因为使用错误代码的替代方法至少会导致同样困难的代码。 David Abrahams 澄清这一点。

Often the decision not to use exceptions is based on the potentially misguided argument that it is difficult to write exception-safe code. Some people say the argument is misguided because using the alternative of using error codes will lead to at least as much difficult code. David Abrahams clarifies this point.

在这个问题上,我很想知道:

In this question, I am curious to know:


  • 在什么情况下你使用例外吗?

  • 您的应用程序的上下文是什么?为什么你不能没有例外地生活?

  • 如何编写异常安全代码?您必须进行多少投资?

  • 是否值得?

  • For what cases do you use exceptions?
  • What is the context of your application? Why can't you live without exceptions?
  • How do you manage to write exception-safe code? What is the level of investment you have to make?
  • Is/Was it worth it?

推荐答案

我将例外用于特殊行为,而不是太频繁。当调试崩溃时,我经常使用异常中断,因此,如果您的代码使用异常来处理通常发生的事情,我将对您发火。

I use exceptions for exceptional behaviour, and not too frequently. When debugging crashes, I frequently use break-on-exception, so if your code is using exceptions to handle things that normally occur, I shall be quietly fuming at you. Use them when things have gone wrong in an unexpected way.

可接受的示例:您的代码所依赖的服务器不可用,因此您的服务无法做任何有意义的事情。

Acceptable example: server your code relies on is unavailable, so your service cannot do anything meaningful.

示例意味着我对您的代码感到恼火:用户输入了一个大于100的数字,作为函数的输入,期望该数字为< = 100。

Example that means I'm annoyed at your code: user entered a number greater than 100, as input to your function which expects a number <=100.

实际上,如果您正在开发面向用户的应用程序,则用户可能不应该做任何会产生异常的事情。

In fact, if you're working on a user-facing application, the user probably shouldn't be able to do anything that generates an exception.

虽然这是一个非常灰色区域,所以如果您同意/不同意,请随时赞成/反对我。如果您不同意,请发表评论说为什么-我很好奇听到其他准则/规则/指标。

This is a very grey area though, so feel free to upvote/downvote me if you agree/disagree. If you disagree please post a comment saying why - I'm curious to hear other guidelines/rules/metrics.

这篇关于您将C ++异常用于什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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