c++可以通过throw语句和try...catch语句实现对异常的处理。
#include <iostream>
using namespace std;
int main()
{
double m ,n;
cin >> m >> n;
try {
if( n == 0)
throw 1; //抛出int类型异常
else
cout << m / n << endl;
}
catch(double d) {
cout << "catch(double) " << d << endl;
}
catch(int e) {
cout << "catch(int) " << e << endl;
}
catch (...) {
cout << "catch (...)" << endl;
}
cout << "finished" << endl;
return 0;
}
编译运行,当输入除数为0时就会抛出异常。
4 0
catch(int) 1
finished
如将throw 1换成throw 0.1就会走到catch(double d)对应的分支,换成throw "12"就会走到catch (...)对应的分支。