C++中的异常处理及捕捉

抛掷异常的程序段:

通过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;
}

猜你喜欢

转载自blog.csdn.net/tmh_15195862719/article/details/81408714