c++异常处理机制示例及讲解(含源代码) 这两天我写了一个测试c++异常处理机制的例子,感觉有很好的示范作用,在此贴出来,给c++异常处理的初学者入门。本文后附有c++异常的知识普及,有兴趣者也可以看看。 下面的代码直接贴到你的console工程中,可以运行调试看看效果,并分析 c++的异常机制。 #include "stdafx.h" #include #include #include // 内存泄露检测机制 #define _CRTDBG_MAP_ALLOC #ifdef _DEBUG #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) #endif // 自定义异常类 class MyExcepction { public: // 构造函数,参数为错误代码 MyExcepction(int errorId) { // 输出构造函数被调用信息 std::cout << "MyExcepction is called" << std::endl; m_errorId = errorId; } // 拷贝构造函数 MyExcepction( MyExcepction& myExp) { // 输出拷贝构造函数被调用信息 std::cout << "copy construct is called" << std::endl; this->m_errorId = myExp.m_errorId; } ~MyExcepction() { // 输出析构函数被调用信息 std::cout << "~MyExcepction is called" << std::endl; } // 获取错误码 int getErrorId() { return m_errorId; } private: // 错误码 int m_errorId; }; int main(int argc, char* argv[]) { // 内存泄露检测机制 _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // 可以改变错误码,以便抛出不同的异常进行测试 int throwErrorCode = 110; std::cout << " input test code :" << std::endl; std::cin >> throwErrorCode; try { if ( throwErrorCode == 110) { MyExcepction myStru(110); // 抛出对象的地址 -> 由catch( MyExcepction* pMyExcepction) 捕获 // 这里该对象的地址抛出给catch语句,不会调用对象的拷贝构造函数 // 传地址是提倡的做法,不会频繁地调用该对象的构造函数或拷贝构造函数 // catch语句执行结束后,myStru会被析构掉 throw &myStru; } else if ( throwErrorCode == 119 ) { MyExcepction myStru(119); // 抛出对象,这里会通过拷贝构造函数创建一个临时的对象传出给catch // 由catch( MyExcepction myExcepction) 捕获 // 在 catch语句中会再次调用通过拷贝构造函数创建...