Part12 异常处理 12.3标准库程序异常处理

标准异常类的继承关系

 

 

 

 

C++标准库各种异常类所代表的异常

 

 

标准异常类的基础
  exception:标准程序库异常类的公共基类
  logic_error表示可以在程序中被预先检测到的异常
    如果小心地编写程序,这类异常能够避免
  runtime_error表示难以被预先检测的异常

 

 

//例12-3 三角形面积计算
//编写一个计算三角形面积的函数,函数的参数为三角形三边边长a、b、c,可以用Heron公式计算:
#include<iostream>
#include<cmath>
#include<stdexcept>
using namespace std;

double area(double a, double b, double c) throw(invalid_argument){
    if(a <= 0 || b <= 0 || c <= 0)
        throw invalid_argument("the side length should be positive");
    if(a + b <= c || b + c <= a || c + a <= b)
        throw invalid_argument("the side length should fit the triangle inequation");
    double s = (a + b + c) / 2;
    return sqrt(s * (s - a) * (s - b) * (s - c));
}
int main(){
    double a, b, c;
    cout << "Please input the side lengths of a triangle: ";
    cin >> a >> b >> c;
    try{
        double s = area(a,b,c);
        cout << "Area: " << s << endl;
    }catch(exception &e){
        cout << "Error: " << e.what() << endl;
    }
    return 0;
}

 

posted @ 2018-01-11 22:32  LeoSirius  阅读(123)  评论(0编辑  收藏  举报