set

    技术2022-05-13  41

    ● 函数的声明 unexpected_handler set_unexpected (unexpected_handler f) throw(); 设置新的,返回旧的 ● 说明 所谓的unexpected_handler,指的是函数。 如果某个函数出现异常,而该异常未被列到异常列表,则unexpected_handler被系统自动调用。 该函数可以调用 terminate 或者 cstdlib::exit 或者 cstdlib::abort 中止程序的执行。 也可以把异常再次抛出,或者抛出别的异常。 如果抛出的异常不在异常列表,而且列表里有 bad_exception,那么系统会代替它抛出 bad_exception。 如果列表里没有 bad_exception,那么系统自动调用 terminate 终止程序的运行。 默认的 unexpected handler 调用 terminate。 ● demo

    #include <iostream> #include <exception> using namespace std; void myunexpected () { cerr << "unexpected called/n"; throw 0; // throws int (in exception-specification) } void myfunction () throw (int) { throw 'x'; // throws char (not in exception-specification) } int main (void) { set_unexpected (myunexpected); try { myfunction(); } catch (int) { cerr << "caught int/n"; } catch (...) { cerr << "caught other exception (non-compliant compiler?)/n"; } return 0; }

     

    在VC2008上运行这个程序时,没有如期的运行myunexpected函数。 正确输出应为: unexpected called caught int 据说GCC是正常的。


    最新回复(0)