异常类型和异常变量的生命周期

    xiaoxiao2023-03-24  4

    #include <iostream> using namespace std; //传统异常处理 int copyfile(char *from, char * to) { if (from==NULL) { cout<<""<<endl; return 1; } if (to == NULL) { return 2; } if (*from == 'a') { return 3; } while(*from!='\0') { *to = *from; to++; from++; } *to = '\0'; return 0; } int main00() { char buf1[]="sbcdefghgjkl"; char buf2[1024]; int ret = copyfile(buf1,buf2); switch (ret) { case 1: cout<<"源出错"<<endl; break; case 2: cout<<"目的出错"<<endl; break; case 3: cout<<"过程出错"<<endl; break; default: cout<<"未知异常"<<endl; break; } printf("buf2:\n",buf2); system("pause"); return 0; } //throw抛异常 void copyfile2(char *from, char * to) { if (from==NULL) { throw 1; } if (to == NULL) { throw 2; } if (*from == 'a') { throw 3; } while(*from!='\0') { *to = *from; to++; from++; } *to = '\0'; } //char*异常 void copyfile3(char *from, char * to) { if (from==NULL) { throw "源异常"; } if (to == NULL) { throw "目的异常"; } if (*from == 'a') { throw "过程异常"; } while(*from!='\0') { *to = *from; to++; from++; } *to = '\0'; } class BadSrc {}; class Badto{}; class BadPro { public: BadPro() { cout<<"BadPro构造函数"<<endl; } ~BadPro() { cout<<"BadPro析构函数"<<endl; } BadPro(const BadPro &obj) { cout<<"BadPro拷贝构造函数"<<endl; } }; //char*异常 void copyfile4(char *from, char * to) { if (from==NULL) { throw BadSrc(); } if (to == NULL) { throw Badto(); } if (*from == 'a') { throw BadPro(); } if (*from == 'b') { throw new BadPro(); } while(*from!='\0') { *to = *from; to++; from++; } *to = '\0'; } int main() { char buf1[]="bbcdefghgjkl"; char buf2[1024]; try { copyfile4(buf1,buf2); } catch (int e) { cout<<"int星异常"<<endl; } catch (char* p) { cout<<"char*异常:"<<p<<endl; } catch (BadSrc e) { cout<<"BadSrc异常:"<<endl; } catch (Badto e) { cout<<"Badto异常:"<<endl; } //结论2:使用引用 会使用throw时的对象 调用一次构造函数 catch (BadPro &e) { cout<<"BadPro &异常:"<<endl; } /* //结论1:如果 接收异常使用异常变量 则调用拷贝构造函数 catch (BadPro e)//是把匿名对象拷贝给e 还是e就是那个匿名对象 { cout<<"BadPro异常:"<<endl; }*/ //结论3:使用指针接收异常 必须手动释放内存 //结论4:使用指针接收异常可以同时和元素 引用类型接收异常写在一块 但是引用接收异常不能同时和使用元素写在一块 catch (BadPro *e) { delete e; cout<<"BadPro *异常:"<<endl; } catch (...) { cout<<"未知异常"<<endl; } printf("buf2:\n",buf2); system("pause"); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1202546.html
    最新回复(0)