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