1.异常的再拋出
#include <QCoreApplication>
#include <exception>
#include <iostream>
#include <stdlib.h>
using namespace std;
int CountTax(int salary)
{
try
{
if(salary < 0)
throw string("zero salary");
cout << "counting tax" << endl;
}
catch(string s)
{
cout << "CountTax error : " << s << endl;
throw; //继续抛出捕获的异常
}
cout << "tax counted" << endl;
return salary * 0.15;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
try
{
CountTax(-1);
cout << "end of try block" << endl;
}
catch(string s)
{
cout << "&&&&&&&&&&&&&:"<< s << endl;
}
cout << "finished" << endl;
return a.exec();
}
2.捕获任何异常的catch语句
#include <QCoreApplication>
#include <exception>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
double m, n;
cin >> m >> n;
try
{
cout << "before dividing." << endl;
if (n == 0.0)
throw - 1; //抛出整型异常
else if(m == 0.0)
throw - 1.0; //拋出 double 型异常
else
cout << m / n << endl;
cout << "after dividing." << endl;
}
catch(double d)
{
cout << "catch (double)" << d << endl;
}
catch(int d)
{
cout << "catch (...)" << d << endl;
}
cout << "finished" << endl;
return a.exec();
}