C++ exception
- C++标准库定义了一套异常体系,有一个exception的抽象基类,其中有一个
const char* what()
的虚函数,用于表示被抛出异常的文字描述 - 我们可以新建自己的异常类,继承于这个抽象基类,那么我们新建的类就可以被任何打算捕获抽象基类的代码所捕获,程序复用性较好。
- 对于自己新建的异常类,我们需要重载实现其what函数,因为基类中这个函数是虚函数
try{}catch{exception& ex}
:一定需要使用引用的形式,否则无法识别特定的异常类
代码
IndexOverflow.h
#ifndef INDEX_OVERFLOW_H #define INDEX_OVERFLOW_H #include <cstdlib> #include <string> #include <iostream> #include <ostream> #include <assert.h> #include <time.h> #include <algorithm> #include <functional> #include <iterator> #include <fstream> #include <vector> #include <typeinfo> #include <sstream> #include <exception> using namespace std; class IndexOverflow : public exception { public: IndexOverflow(int index, int maxi) : _index(index), _max(maxi) { } const char* what() const { ostringstream ex_msg; static string msg; ex_msg << "current index : " << _index << " exceeds max index : " << _max; msg = ex_msg.str(); return msg.c_str(); } private: int _index; int _max; }; #endif
MyArray.h
#ifndef MY_ARRAY_H #define MY_ARRAY_H #include "IndexOverflow.h" class MyArray { public: MyArray(int num) :_num(num) { arr = new int[num]; } ~MyArray() { delete[] arr; } const int operator[] (const int& index) const { try { if (index < 0 || index >= _num) { throw IndexOverflow(index, _num); } } // 必须使用引用的方式传参,否则会出现unknown exception的问题 catch (exception& ex) { cout << ex.what() << endl; return 0; } return arr[index]; } private: int _num; int *arr; }; #endif
main.cpp
#include "MyArray.h" using namespace std; typedef long long ll; void test() { MyArray arr(5); cout << arr[5] << endl; } int main() { // 按照时间来初始化种子,保证每次结果不一样 srand( (int)time(0) ); //cout << rand() << endl; test(); system("pause"); return 0; }