抛掷异常的程序段:
通过throw语句抛出异常
void fun
{
throw();
}
捕获异常的程序段:
将可能出现异常的语句放在try里
try
{};
catch
{};
int Div(int x,int y); //可以抛出任何异常
int Div(int x,int y) throw(); //不可以抛出任何异常
int Div(int x,int y) throw(int ,char); //可以抛出 int char 类型的异常
#include<iostream>
using namespace std;
/*int Div(int x,int y)
{
if(y==0)
{
throw 0;
}
else
return x/y;
}*/
//int Div(int x,int y); //可以抛出任何异常
//int Div(int x,int y) throw(); //不可以抛出任何异常
int Div(int x,int y) throw(int ,char); //可以抛出 int char 类型的异常
int f(int x,int y)
{
try
{
Div(x,y);
}
catch(int)
{
throw 'a';
}
}
int main()
{
int a,b;
cout << "Please input: " << endl;
cin >> a >> b;
try
{
// cout << Div(a,b) << endl;
cout << f(a,b) << endl;
}
catch(int)
{
cout << "Int Zero Exception!" << endl;
}
catch(char)
{
cout << "Char Zero Exception!" << endl;
}
return 0;
}
int Div(int x,int y) throw(int ,char)
{
if(y==0)
{
throw 0;
}
else
return x/y;
}