标准库异常处理
C++提供了一组标准异常类,这些类以基类Exception开始,标准程序库抛出的所有异常,都是派生于该基类,这些异常类的继承关系如下:
该基类提供一个成员函数what(),用于返回错误信息,声明如下:
virtual const char* what() const throw();
下表列出了各个具体异常类的含义及定义他们的头文件。runtime_error和logic_error是一些具体异常类的基类,它们分别表示两大类异常。logic_error表示那些可以在程序中被预先检测到的异常,也就是如果精心地编写程序,这类异常能够避免;而runtime_error则表示那些难以避免的错误。
一些编译语言规定只能抛出某个类的派生类对象,如Java中的Exception类。C++中没有这个强制要求,但仍然可以这样实践。例如, 在程序中可以使所有的异常皆派生自Exception或其子类,或者直接抛出标准库提供的异常类型,这样做会带来很多方便
logic_error和runtime_error
这两个类及其派生类,都有一个接收const string&型参数的构造方法。在构造异常对象时需要将具体的错误信息传递给该函数,如果调用该对象的what函数,就可以得到构造时提供的错误信息。
在计算三角形面积的函数中需要判断输入的参数 a, b, c是否构成一个三角形,若不能构成,则需要抛出异常。
#include <iostream>
#include <string.h>
#include <math.h>
#include <exception>
#include <stdexcept>
double area(double a, double b, double c){
if(a <= 0 || b <= 0 || c <= 0){
throw invalid_argument("the side length should be positive!\n");
}
if(a+b <= c || a+c <= b || b+c <= a){
throw invalid_argument("the side length should be positive!\n");
}
double p = (a+b+c)/2;
return sqrt(p * (p-a) * (p-b) * (p-c));
}
int main() {
double a, b, c;
printf("Please input the side length of a triangle:\n");
cin >> a >> b >> c;
try{
double s = area(a, b, c);
printf("Area: %f\n", s);
}catch(exception& e){
printf("Error: %s\n", e.what());
}
return 0;
}