C++ throw的实验 & 异常类继承关系

如果定义了 throw() 表示函数不抛出异常,这时候如果还是抛出,会导致运行时错误。

#include <iostream>
#include <exception>
#include <stack>

using namespace std;

void func() throw() {
    int x = 5;
    throw x;
}

int main() {
    std::cout << "Hello, World!" << std::endl;

    try {
        func();
    }
    catch(int &x) {
        std::cout << x << endl;
    }
    catch (...) {
        cout << "here catch" << endl;
    }

    return 0;
}
View Code

 

运行:

libc++abi.dylib: terminating with unexpected exception of type int

 

如果去掉 throw(),那么就可以了:

Hello, World!
5
View Code

 

 

注意,stack pop空的异常抓不住,只有throw出来的异常才能抓的住。

 

posted @ 2017-02-19 15:34  blcblc  阅读(1316)  评论(0)    收藏  举报