C ++ rethrow不会调用自定义终止处理程序

时间:2015-04-24 07:55:34

标签: c++ exception throw

我使用了自定义终止处理程序,如果我使用类型调用throw或显式调用terminate(),但是如果我使用rethow,即throw; ,不调用自定义终止处理程序,只调用默认的终止处理程序,导致程序中止。代码确认C ++ 03。任何人都可以帮我找出问题吗?提前谢谢

#include <iostream>       
#include <exception>      
using namespace std;

void myunexpected() {
    cerr << "CUSTOM unexpected handler called ------ \n";
    throw 0;     // throws int (in exception-specification)
}
void myterminate () {
  cerr << "CUSTOM terminate handler called ------ \n";
  //abort();  // forces abnormal termination
  exit(0);
}
void myfunction() throw (int) {
    throw 'x';   // throws char (not in exception-specification)
}

int main(void) {
    set_unexpected(myunexpected);
    set_terminate(myterminate);
    int a = 1;
    try{
        try {
            myfunction();
        }
        catch (int) {
            cerr << "caught int\n";
            throw string("sree");
        }
        catch (...) { cerr << "caught some other exception type\n"; }
    }
    catch (string& s)
    {
        cerr << a << "caught STRING " << s << endl;
        //throw 0;     //ok --> implicitly calls terminate()-->myterminate
        //terminate(); //ok --> explicitly calls terminate()-->myterminate
        throw;  //--------- Calls default throw Why ??? 

    }
    return 0; 
} 

输出

CUSTOM unexpected handler called ------
caught int
1caught STRING sree

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

--------------------------------
Process exited after 8.238 seconds with return value 255
Press any key to continue . . .

0 个答案:

没有答案