Chinaunix首页 | 论坛 | 博客
  • 博客访问: 191113
  • 博文数量: 20
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 290
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-16 13:08
文章分类

全部博文(20)

文章存档

2010年(1)

2009年(10)

2008年(9)

我的朋友

分类: C/C++

2009-10-14 16:14:55


结构化异常SEH转化为C++标准异常的简单实现


#include "stdafx.h"
#include <windows.h>
#include <stdio.h>

#include <eh.h> // For _set_se_translator

class CSE
{
public:
    
    //Call this function for each thread.

    static void MapSEtoCE()
    {
        _set_se_translator(TranslateSEtoCE);
    }
    
//  operator DWORD()
//  {
//      return(m_er.ExceptionCode);
//  }

    DWORD GetExpCode() { return m_er.ExceptionCode; }
    
private:
    
    CSE(PEXCEPTION_POINTERS pep)
    {
        m_er = *pep->ExceptionRecord;
        m_context = *pep->ContextRecord;
    }
    
    static void _cdecl TranslateSEtoCE(UINT dwEC,
        PEXCEPTION_POINTERS pep)
    {
        throw CSE(pep);
    }
    
private:
    EXCEPTION_RECORD m_er; // CPU independent exception information
    CONTEXT m_context;     // CPU dependent exception information
};


int main(int argc, char* argv[])
{
    CSE::MapSEtoCE();

    try
    {
//     *(PBYTE) 0 = 0; // Access violation
        int x = 0;
        x = 5 / x;     // Division by zero
    }
    catch(CSE& se)
    {
        //switch(se) // Calls the operator DWORD() member function
        switch(se.GetExpCode())
        {  
        case EXCEPTION_ACCESS_VIOLATION:
            // This code handles an access-violation exception
            printf("EXCEPTION_ACCESS_VIOLATION\n");
            break;
            
        case EXCEPTION_INT_DIVIDE_BY_ZERO:
            // This code handles a division-by-zero exception
            printf("EXCEPTION_INT_DIVIDE_BY_ZERO\n");
            break;
            
        default:
            // We don't handle any other exceptions
            //throw; // Maybe another catch is looking for this
            break;   // Never executes
        }
    }

    printf("exit!\n");
    return 0;
}


阅读(1522) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~