1 异常处理基本思想
①处理除0异常,异常发生后续语句不执行
#include <iostream>
using namespace std;
int divede(int x, int y) {
if (y == 0)
throw x; //抛出异常
return x / y;
}
int main()
{
try { //可能发生异常的调用写在try里
cout << "5 / 2 = " << divede(5, 2) << endl;
cout << "3 / 0 = " << divede(3, 0) << endl;
cout << "7 / 3 = " << divede(7, 3) << endl;
}
catch (int e) { //捕获异常,此处类似函数实参传至形参
cout << e << " cannot be divided by 0" << endl; //发生异常的处理方式
}
return 0;
}
输出:
5 / 2 = 2
3 cannot be divided by 0
![在这里插入图片描述](https://img-blog.csdnimg.cn/8c330a3f275f4c2c87ecb1beaedbe438.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_Q1NETiBAa2Fua2FuXzIwMjEwNA==,size_23,color_FFFFFF,t_70,g_se,x_16)
2 异常处理中的构造与析构
#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 << "接下来抛掷异常" << endl;
throw MyException("exception thrown bt func");
}
int main() {
try {
func(); //func可能发生异常,放到try中
} //先结束try语句,再catch,因此try中构造的Demo对象d先析构
catch (MyException& e) { //异常对象为类的对象引用
cout << "Caught an exception:" << e.getMessage() << endl;
}
cout << "main contunue" << endl;
return 0;
}
输出:
Constructor of Demo
接下来抛掷异常
Destructor of Demo
Caught an exception:exception thrown bt func
main contunue
3 标准程序库异常处理
异常类继承关系
基类:exception
各种异常类所代表的异常
#include <iostream>
#include <string>
#include <stdexcept>
#include <cmath> //数学常用库
using namespace std;
double area(double a, double b, double c) throw(invalid_argument){ //throw中写可能发生的异常类型
if (a <= 0 || b <= 0 || c <= 0)
throw invalid_argument("the side length should be positive");//用"xxx"初始化一个invalid_argument对象
if (a + b <= c || a + c <= b || b + c <= 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 {
cout << "Area:" << area(a, b, c) << endl;
}
catch (exception &e){ //统一用基类对象
cout << "Error:" << e.what() << endl; //what()函数可以调用输入的错误信息
}
return 0;
}
输入输出1:
Please input the side lengths of a triangle: -1 4 6
Error:the side length should be positive
输入输出2:
Please input the side lengths of a triangle: 1 2 3
Error:the side length should fit the triangle inequation
输入输出3:
Please input the side lengths of a triangle: 3 4 5
Area:6