28.异常机制的处理原理

三步骤:try——throw——catch

#include<iostream>
using namespace std;

float Div(int a, int b){
	if(b == 0){
		throw b;  //抛出异常,从右边返回,return不执行,直接跳到catch
	}
	return a/b;  //从左边返回,返回类型为float
}

void main(){
	int a = 10;
	int b = 100;
	float result = 0.0f;
	try{
		float result = Div(a,b);
	}
	catch(int){  //针对类型进行 catch
		cout<<"Div Error, b == 0"<<endl;
	}
	catch(short){
		cout<<"Div Error, b == 0"<<endl;
	}
	catch(...){  //catch all,只能放到最后
		cout<<"Div Error, b == 0"<<endl;
	}
	cout<<"result = "<<result<<endl;
}

throw 是从右边抛出的,不执行下面的程序,直接执行 catch 程序。

异常规范

实际上 VC6.0 不支持,所以最好还是不写 throw。

float Div(int a, int b)throw(){
	if(b == 0){
		throw b;  //抛出异常,从右边返回,return不执行,直接跳到catch
	}
	return a/b;  //从左边返回,返回类型为float
}

版权声明:本文为博主原创文章,如有错误,恳请大家在评论区指出,在下不胜感激~如要转载注明出处即可~

猜你喜欢

转载自blog.csdn.net/Wonz5130/article/details/81408286
今日推荐