1、处理除零异常
#include <iostream>
using namespace std;
int divide(int x, int y){
if(y == 0)
throw x;
return x/y;
}
int main(int argc, char* argv[]){
try{
cout << "5/2 = " << divide(5, 2) << endl;
cout << "8/0 = " << divide(8, 0) << endl;
cout << "7/1 = " << divide(7, 1) << endl;
}catch(int e){
cout << e << " is divide by zero!" << endl;
}
cout << "That is ok." << endl;
return 0;
//5/2 = 2
//8 is divided by zero!
//That is ok.
}
2、异常接口声明
可以在函数的声明中列出这个函数可能抛掷的所有异常类型
例如
void fun() throw(A, B, C, D);
若无异常接口声明,则此函数可以抛掷任何类型的异常
不抛掷任何类型异常的函数声明如下:
void fun() throw();
3、异常处理中的构造和析构
自动的析构
找到一个匹配的catch异常处理后
初始化异常参数
将从对应的try块开始到异常被抛掷处之间构造(且尚未析构)的所有自动对象进行析构
从最后一个catch处理之后开始恢复执行
#include <iostream>
#include <string>
using namespace std;
class MyException{
public:
MyException(const string &message):message(message){}
~MyException(){}
const string &getMessage() const { return message; }
private:
string message;
};
class Demo{
public:
Demo(){cout << "Constructor of Demo" << endl;}
~Demo(){cout << "Destructor of Demo" << endl;}
};
void func() throw(MyException){
Demo d;
cout << "Throw MyException is func()" << endl;
throw MyException("exception thrown by func()");
}
int main(){
cout << "In main function" << endl;
try{
func();//在接受异常时,由异常处理机制将d析构
}catch(MyException& e){
cout << "Caught an exception:" << e.getMessage() << endl;
}
cout << "Resume the execution of main()" << endl;
return 0;
//In main function
//Constructor of Demo
//Throw MyException in func()
//Destructor of Demo
//Caught an exception:exception thrown by func()
//Resume the execution of mian()
}
4、标准程序库异常处理
标准异常类:标准库中定义的与异常处理相关的类
标准异常类的基础
exception:标准程序库异常类的公共基类
logic_error表示可以在程序中被预先检测到的异常
如果小心地编写程序,这类异常能够避免
runtime_error表示难以被预先检测的异常
#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 || a+c <= b || c+b <= a)
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;//e.what()返回异常对象中的字符串,异常的原因
return 0;
}