标准异常类
#include "stdafx.h"
#include "iostream"
#include "Vector"
#include <stdexcept>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector <int> nums(10,1);
try
{
cout << nums.at(1) << endl;
cout << nums.at(11) << endl; // at()访问越界元素时会抛出out_of_range异常
cout << nums.at(2) << endl;
}
catch (out_of_range e)
{
cout << e.what() << endl; // what() 输出异常信息
}
cout << nums.at(3) << endl;
return 0;
}
自定义的异常
class CException
{
public:
string msg;
CException(string errmsg):msg(errmsg){}
};
double Devide(double num1, double num2)
{
if (num2 == 0)
{
throw CException("devide by zero"); // 抛出自定义异常
}
return num1 / num2;
}
int _tmain(int argc, _TCHAR* argv[])
{
try
{
cout << "result=" << Devide(16, 0) << endl;
}
catch (CException e)
{
cout << e.msg.c_str() << endl;
}
return 0;
}