代码改变世界

异常处理

2018-10-21 21:18  mengjuanjuan1994  阅读(121)  评论(0编辑  收藏  举报

1. 异常基本语法

#include<iostream>
using namespace std;
int divide(int x, int y)
{
if(y == 0)
{
throw y;
}
return x / y;
}
int main()
{
try
{
cout << "5 / 2 = " << divide(5, 2) << endl;
cout << "5 / 0 = " << divide(5, 0) << endl;
cout << "8 / 2 = " << divide(8, 2) << endl;
}
catch(int e)
{
cout << "除数为" << e << endl;
}
system("pause");
return 0;
}

2. 异常接口声明

2.1 可以在函数的声明中列出这个函数可能抛掷的所有异常类型

void fun() throw (int, char, string)

{

}

2.2 若无异常接口声明,则此函数可以抛掷任何类型的异常

void fun()

{

}

2.3 不抛掷任何类型异常的的函数声明如下

void fun() throw()

{

}

3. 异常处理中的构造与析构(栈解旋)

析构是自动调用的

找到一个匹配的catch处理后:

(1)初始化异常参数(异常参数一般用引用),执行catch处理

(2)将对应的try块开始到异常被抛掷处之间构造(且尚未析构)的所有自动对象进行析构

(3)从最后一个catch处理之后开始恢复执行

4. 标准程序库异常处理

eg: 三角形面积的计算

#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;

double area(double a, double b, double c)
{
if (a <= 0 || b <= 0 || c <=0)
{
throw invalid_argument("三角形的边长不能为0");
}
if (a + b <= c || b + c <= a || a + c <= b)
{
throw invalid_argument("三角形的三条边不能构成三角形");
}
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
int main()
{
double a, b, c;
cin >> a >> b >> c;
try
{
double s = area(a, b, c);
cout << s << endl;
}
catch(exception &e)
{
cout << "Error: " << e.what() << endl;
}
system("pause");
return 0;
}