学习c++ 的异常捕捉模块,写了个测试例子,本来打算让线程t2整除0挂掉,然后顺便测试下死锁,结果出现了mutex destroy while busy
#include#include "noticer.h" #include "observer.h" #include "xx.h" #include "single.h" #include #include #include using namespace std; int share = 1; void t1() { for (int i = 0; i < 1000; i++) { mutex m; m.lock(); share++; printf("t1:%dn", share); m.unlock(); } } void t2() { for (int i = 0; i < 100; i++) { try { mutex m; m.lock(); printf("33333333333333333333333n"); //Sleep(5000); throw 1; share = 99999; printf("t2:%dn", share); m.unlock(); } catch (...) { printf("catcatfatdafdgasgstatn"); } } printf("222222222222222222222222222222222222222n"); } void test() { int y = 0; int a[100]; try { a[1010] = 3; } catch (...) { cout << "teststet" << endl; } } int main() { //thread x(t1); //printf("1111111111111111111n"); //thread y(t2); //mutex m; //m.lock(); //share=-1000; //m.unlock(); //printf("main:%dn", share); //x.join(); //y.join(); int y = 0; int a[100]; try { cout << "error" << endl; test(); //throw 1; //int x = 5 / y; a[1001] = 10; } catch(...) { cout << "catch" << endl; } //single::getinstance()->pri(); // //single::getinstance()->pri(); // xx *p = new xx; //cout << "main start" << endl; //noticer ticket; //observer buyer1; //observer2 buyer2; //ticket.attach(&buyer1); //ticket.attach(&buyer2); //ticket.attach(&buyer2); //ticket.attach(&buyer2); //ticket.attach(&buyer2); //for (int i = 1; i < 100; i++) //{ // ticket.doprocess(i); //} } }
和python不同的是,c++并不是出现了错误就能被调用者(这里是main)捕捉,或者更深入的解释是,整除0的时候,并不能主动的抛出错误。
标准做法是,首先判断除数是否为零,如果不是则继续运算。如果除数是0,且是合法输入,那么必定有约定好的输出,或约定好没有输出。如果是非法输入,则输出错误信息,或抛出异常,或其他约定好的错误处理方式。不应过度依赖异常处理。——c++本身并不会抛出除零异常,所以必须手动检查之后手动抛出异常(如果需要的话)。如果要抛出异常,可以抛出invalid_argument,或者自定义异常。
。



