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

来源:互联网 发布:nba总决赛数据2016 编辑:程序博客网 时间:2024/05/21 23:33
//动态异常声明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()终止了程序的运行。