C++异常处理机制
#includeiostream #includeexception using std::exception; using namespace std; class CMyException : public exception { public: CMyException(int num) :exception(数组越界) { m_num num; } char const* what() const { cout 数组下标 m_num 越界了 endl; return exception::what(); } private: int m_num; }; templateclass T class CMyArray { private: T* m_pArr; int m_nSize; public: CMyArray(int nSize) { m_nSize nSize; m_pArr new T[m_nSize]; } T operator[](int nIndex) { if (nIndex 0 || nIndex m_nSize) { throw CMyException(nIndex); } return m_pArr[nIndex]; } ~CMyArray() { if (m_pArr ! NULL) { delete[] m_pArr; m_pArr NULL; } } }; int main(int agvn, char* agvc[]) { CMyArraychar arr(5); try { arr[12] a; } catch (CMyException e) { cout e.what() endl; } return 0; }使用三个关键字throw抛出异常try是否触发异常catch处理