try/catch/throw

Pearl ·
更新时间:2024-09-20
· 793 次阅读

try/catch/throw

try/catch/throw的优点:
1.可以自定义抛出异常之后的操作
2.异常抛出后会一直返回调用函数(或者说上一层函数),直到被catch到,所以便可以统一将catch语句写在一起,使代码更加方便整洁。

1.遇到除0时的异常 void test1() { try { double m, n; cin >> m >> n; if (n == 0) throw -1; if (m == 0) throw - 1.0; cout << m / n << endl; } catch (int i) { cout << "throw int:" << i << endl; } catch (const char* s) { cout << "throw const char*:" << s << endl; } catch (double d) { cout << "throw double:" << d << endl; } catch (...) { cout << "throw ..." << endl; } cout << "try/catch finished" << endl; }
2.throw出来的异常返回上一层函数 void help2() { try { throw - 1; } catch (char c) { cout << "catch char:" << c << endl; } cout << "help2 finished" << endl; } void test2() { try { help2(); cout << "try in test2 finished" << endl; } catch (...) { cout << "catch exception" << endl; } }
3.可以throw 出类,并且不断返回上一层函数 class Base { public: Base() {}; Base(string s) :_s(s) {}; string _s; }; void help3() { //throw "sd";//throw不一定要在try里面进行 try { Base b("BBBBBBBBBBase"); throw 'a';//不断修改这里throw的对象进行测试 cout << "try in help3 finished" << endl; } catch (Base b) { cout << "catch Derived:" << b._s << endl; } cout << "help3 finished" << endl; } void test3() { try { help3(); cout << "try int test3() finished" << endl; } catch (int i) { cout << "catch int :" << i << endl; } catch (...) { cout << "catch Exception" << endl; } cout << "test3() finfished" << endl; }
4.自己写一个exception的派生类,实现对what函数的使用
函数后面加上throw()表示异常申明
void func() throw(int i, double d) 表示func函数可以抛出int,double型的异常
void func() throw() 则不会抛出任何异常 struct myException:public exception{ const char* what()const throw() { return "this is myException"; } }; void test4() { try { myException e; throw(-1); } catch (myException& e) { cout << e.what() << endl; } catch (exception& e) { cout << "catch exception" << endl; } catch (...) { cout << "..." << endl; } }
作者:Worthy_Wang



throw catch try

需要 登录 后方可回复, 如果你还没有账号请 注册新账号