您的位置:首页 > 编程语言 > C语言/C++

C++11新特性学习笔记—noexcept关键字

2017-11-03 14:28 295 查看
//动态异常声明thro由于很少使用,在c++11中被弃用了
//表示函数不会抛出异常的动态异常声明throw()也被新的noexcept异常声明所取代
//noexcept修饰的函数不会抛出异常
//在c++11中,如果noexcept修饰的函数抛出了异常,编译器可以选择直接调用std::terminate()
//来终止程序的运行,这比基于异常机制的throw()在效率上会高出一些。
//使用noexcept可以有效的阻止异常的传播与扩散

#include <iostream>

using namespace std;

void throw_(){ throw 1; }
void NoBlockThrow(){ throw_(); }

void BlockThrow() noexcept { throw_(); }

int main()
{
/*try
{
throw_();
}
catch (...)
{
cout << "found throw." << endl;
}
try
{
NoBlockThrow();
}
catch (...)
{
cout << "throw is not blocked" << endl;
}*/

try
{
BlockThrow();
}
catch (...)
{
cout << "found throw 1" << endl;
}
//noexcept修饰的函数抛出了异常,编译器可以选择直接调用std::terminate()
//来终止程序的运行,
}
这个程序运行的时候,前两个try catch会正常输出xx到控制台,最后一个try-catch块,程序会弹出错误框表示程序已被终止,这就是因为如果noexcept修饰的函数抛出了异常,那么编译器就直接调用std::terminate()终止了程序的运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++11