例子:
using namespace std;
void throwException(){ throw 1;}
void noBlockThrow(){ throwException();}
void blockThrow() noexcept {throwException();}
int main(){
try {
throwException();
}catch(...) {
cout << "Found throw." << endl;
}
try {
noBlockThrow();
}catch(...) {
cout << "Throw is not blocked." << endl;
}
try {
blockThrow();
}catch(...) {
cout << "Found throw 1." << endl;
}
}
通过xcode,运行结果如下:
Found throw.
Throw is not blocked.
libc++abi.dylib: terminating with uncaught exception of type int
调用blockThrow抛出异常会导致程序退出。当函数声明了noexcept但抛出异常的话,会调用std::terminate中断程序的执行,从而阻止异常的传播。
noexcept的另一种用法是形如
void except_func() noexcept(常量表达式);
常量表达式结果为true表示函数不会抛出异常,反之可能抛异常。
C++11中,析构函数和delete函数默认为noexcept,但是如果代码显示地为析构函数指定了noexcept,或者类的基类或成员有noexceot(false)的析构函数,析构函数就不会再保持默认值。
网友评论