⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo_exception_handling_3.cpp

📁 对于一个初涉VC++的人来书
💻 CPP
字号:

//****************************************************
// 在函数声明中进行异常情况指定: VC编译器似乎不支持?
//****************************************************

# include <iostream.h>
# include <math.h>

//double triangle(double a,double b,double c) throw(double);
//double triangle(double a,double b,double c) throw(int); //Warning: C++ Exception Specification ignored
double triangle(double a,double b,double c) throw();
//double triangle(double a,double b,double c);

int main()
{
	cout<<"begin of main()"<<endl;
	cout<<endl;

	double a,b,c,area;

	cout<<"input three sides of triganle: ";
	cin>>a>>b>>c;

	//try块进行异常检测: 对三角形条件进行检查
	try
	{
		while(a>0 && b>0 && c>0)
		{
			area=triangle(a,b,c);
			cout<<"area of triangle is: "<<area<<endl;
			cout<<endl;
			cout<<"input three sides of triganle: ";
			cin>>a>>b>>c;
		}
	}

	catch(double)  //捕获异常并作相应处理
	{
		cout<<"a="<<a<<",b="<<b<<",c="<<c<<": that is not a traingle!"<<endl;
	}
	
	cout<<endl;
	cout<<"end of main()"<<endl;
	
	return 0;
}
  
//异常指定是函数声明和函数定义的组成部份,否则会类型不匹配
//double triangle(double a,double b,double c) throw(double)
//double triangle(double a,double b,double c) throw(int) //Warning: C++ Exception Specification ignored
double triangle(double a,double b,double c) throw()
//double triangle(double a,double b,double c)
{
	cout<<"begin of triangle()"<<endl;

	double s=(a+b+c)/2,area;
	
	//当不符合三角形条件则抛出异常信息
	if(a+b<=c||b+c<=a||c+a<=b) throw a; 

	area=sqrt(s*(s-a)*(s-b)*(s-c));

	cout<<"end of triangle()"<<endl;

	return area;
}

/*
begin of main()

input three sides of triganle: 3 4 5
begin of triangle()
end of triangle()
area of triangle is: 6

input three sides of triganle: 1 2 1
begin of triangle()
a=1,b=2,c=1: that is not a traingle!

end of main()
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -