这两天我写了一个测试c++异常处理机制的例子,感觉有很好的示范作用,在此贴出来,给c++异常处理的初学者入门。本文后附有c++异常的知识普及,有兴趣者也可以看看。
下面的代码直接贴到你的console工程中,可以运行调试看看效果,并分析c++的异常机制。
- #include "stdafx.h"
-
#include<stdlib.h>
-
#include<crtdbg.h>
-
#include <iostream>
-
-
#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);
-
-
-
-
-
-
throw &myStru;
- }
-
else if ( throwErrorCode == 119 )
- {
- MyExcepction myStru(119);
-
-
-
-
-
-
throw myStru;
- }
-
else if ( throwErrorCode == 120 )
- {
-
-
-
-
-
MyExcepction * pMyStru = new MyExcepction(120);
-
throw pMyStru;
- }
-
else
-
请发表评论