400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

C++怎么使用异常发信号

这篇文章主要讲解了“C++怎么使用异常发信号”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++怎么使用异常发信号”吧!

我们提供的服务有:成都网站设计、网站制作、微信公众号开发、网站优化、网站认证、武川ssl等。为近1000家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的武川网站制作公司

如果必要任务失败了,使用异常发信号

Reason(原因)

It should not be possible to ignore an error because that could leave the system or a computation in an undefined (or unexpected) state. This is a major source of errors.

错误可能会让系统或计算处于没有定义(或者意外)的状态,应该杜绝错误被忽略的可能性。忽略对错误的处理是大部分问题的主要原因。

Example(示例)

int printf(const char* ...);    // bad: return negative number if output fails
template // good: throw system_error if unable to start the new threadexplicit thread(F&& f, Args&&... args);
Note(注意)

What is an error?

什么是错误?

错误意味着功能无法达成它对外宣称的目的(包括建立事后条件)。忽略错误的调用代码可能造成错误的结果或者没有定义的系统状态。例如,无法连接到远程服务器不是它自己造成的错误:服务器可能因为各种原因拒绝连接,因此自然的做法就是返回一个结果让调用者确认。如果无法连接被认为是错误,这个失败应该抛出异常。

Exception(异常)

Many traditional interface functions (e.g., UNIX signal handlers) use error codes (e.g., errno) to report what are really status codes, rather than errors. You don't have a good alternative to using such, so calling these does not violate the rule.

很多传统的函数(例如UNIX信号量处理函数)使用错误码(例如errno)报告实际的状态。由于没有好的选项来代替它们,因此调用这些函数不算违反规则。

Alternative(可选项)

If you can't use exceptions (e.g., because your code is full of old-style raw-pointer use or because there are hard-real-time constraints), consider using a style that returns a pair of values:

如果不能使用异常(例如,因为代码到处都是旧风格的原始指针,或者存在硬实时约束),考虑使用返回结果对的风格。

int val;int error_code;tie(val, error_code) = do_something();if (error_code) {    // ... handle the error or exit ...}
// ... use val ...

译者注:tie是C++引入的新特性,用于解包同样是C++11引入的tuple数据。

This style unfortunately leads to uninitialized variables. Since C++17 the "structured bindings" feature can be used to initialize variables directly from the return value:

这个方式有一个缺点就是会导致未初始化变量。使用C++17之后导入的结构化绑定功能可以通过返回值直接初始化变量。

auto [val, error_code] = do_something();if (error_code) {    // ... handle the error or exit ...}// ... use val ...

Note(注意)

We don't consider "performance" a valid reason not to use exceptions.

我们不认为“性能”是不使用异常的合理原因。

       对于性能敏感的代码来说,将检查部分移到代码的关键部分之外是一个好方法。

Enforcement(实施建议)

感谢各位的阅读,以上就是“C++怎么使用异常发信号”的内容了,经过本文的学习后,相信大家对C++怎么使用异常发信号这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


当前标题:C++怎么使用异常发信号
标题URL:http://mbwzsj.com/article/jiohod.html

其他资讯

让你的专属顾问为你服务