异常处理

例一:

#include<iostream>
using namespace std;

//double div(double x, double y) throw(int, double) //限制抛出的类型,如不匹配,直接抛给内核
//double div(double x, double y) throw() //直接抛给内核
double div(double x, double y) //没有限制
{
	if(y==0)
		throw "exception";
	cout<<"div(x, y)"<<endl;
	return x/y;
}

void main()
{
	try{
		try{
			divison(5, 0);
		}
		catch (int errcode){
			cout << "div can't be 0!" << errcode << endl;

			//throw 10;
			throw;//继续抛一样的
		}
		catch (double errcode){
			cout << "div can't be 0.0!" << errcode << endl;

			//throw 10.0;
			throw;
		}
		catch (...){//其他类型异常
			cout << "div can't be 0.0!" << endl;

			throw;
		}
	}
	catch (int errcode){
		cout << "div can't be 0.0!" << errcode << endl;

	}
	catch (double errcode){
		cout << "div can't be 0.0!" << errcode << endl;

	}
	catch (...){//其他类型异常
		cout << "div can't be 0.0!" << endl;

	}
	cout << "main end!" << endl;

}

例二:异常嵌套

#include<iostream>
using namespace std;

double division(double x, double y) throw()
{
	if (y == 0)
		//throw  "exception";
		throw 100;
	cout << "div(x,y)" << endl;
	
	return x / y;
}

void fun()
{
	try{
		division(5, 0);
	}
	catch (int errCode)
	{
		cout << "first exception, " << errCode << endl;
		throw;
	}
}

int main(void)
{
	try{
		fun();
	}
	catch (int errCode){
		cout << "catched exception, " << errCode << endl;
	}
	catch (double errCode){
		cout << "catched exception, " << errCode << endl;
	}
	catch (...){//其他类型异常
		cout << "catched ..." << endl;
	}

	cout << "main end" << endl;

	return 0;
}

例三:异常类

#include<iostream>
using namespace std;

class MyException
{
	public:
		MyException(string errInfo="unknown", int errNo=0)
			:errInfo(errInfo), errNo(errNo)
		{
			cout<<"MyException()"<<endl;
		}
		~MyException()
		{
			cout<<"~MyException()"<<endl;
		}
		MyException(const MyException &)
		{
			cout << "MyException(MyException&)" << endl;
		}
		void out()
		{
			cout<<"no:"<<errNo<<", info:"<<errInfo<<endl;
		}
	private:
		string errInfo;
		int errNo;
};

void fun(int code)
{
	if(code==110)
	{
		//throw MyException("terrist", 110);//首选,保证唯一性,且在传递时不会丢失
		MyException temp("terrist", 110);
		throw temp;
		
	}
	if(code==120)
	{
		MyException *MyEx=new MyException("help", 120);
		throw MyEx;
	}
	if(code==119)
	{
		MyException MyEx("fire", 119);
		throw &MyEx; //不要返回局部变量的地址
	}
}

main()
{
	cout<<"please input errnun:";
	int code;
	cin>>code;

	try{
		fun(code);
	}/*catch(MyException &MyEx)   //类型为MyException的异常将会-->
	{
		cout<<"reference"<<endl;
		MyEx.out();
	}*/catch(MyException MyEx)    //-->为MyException更早的处理者所捕获
	{
		cout<<"value"<<endl;
		MyEx.out();
	}catch(MyException *MyEx)
	{
		cout<<"pointer"<<endl;
		MyEx->out();
		
		//对于120而言才需要;
		delete MyEx;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值