也可以编写自己的类异常
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
int fn(int a, int b)
{
if (b == 0)//函数的编写者要自己把所有的出错可能性都考虑进去
{
throw 1; //抛出int类型异常
//throw 3.14; //抛出double类型异常
//throw 'a';//抛出char类型异常
}
return a / b;
}
void test01()
{
int a = 10;
int b = 0;
//异常必须处理,如果不处理 就挂掉
try
{
fn(a, b);
}
catch (int) //捕获异常
{
cout << "int类型异常" << endl;
}
catch (double)
{
throw;//如果不想处理这个异常 ,可以继续向上抛出
cout << "double类型异常" << endl;
}
catch (...)
{
cout << "其他类型异常" << endl;
}
}
int main() {
try
{
test01();
}
catch (char) //如果异常都没有处理,那么成员terminate函数,使程序中断
{
cout << "main 函数中 double类型异常" << endl;
}
catch (...)
{
cout << "main函数中 其他类型异常" << endl;
}
system("pause");
return EXIT_SUCCESS;
}