为什么这个程序不能输出正确的异常?

时间:2013-06-27 07:02:58

标签: c++ windows visual-c++

以下程序仅输出:

0In finally

而不是输出:

0 In trans_func Caught a __try exception with SE_Exception In finally

正如我所料。

#include "stdafx.h"

// crt_settrans.cpp
// compile with: /EHa
#include <stdio.h>
#include <windows.h>
#include <eh.h>

void SEFunc();
void trans_func( unsigned int, EXCEPTION_POINTERS* );

class SE_Exception
{
  private:
    unsigned int nSE;
  public:
    SE_Exception() {}
    SE_Exception( unsigned int n ) : nSE( n ) {}
    ~SE_Exception() {}
    unsigned int getSeNumber() { return nSE; }
};

int main( void )
{
    try
    {
        _set_se_translator( trans_func );
        SEFunc();
    }
    catch( SE_Exception e )
    {
        printf( "Caught a __try exception with SE_Exception.\n" );
    }

    system("pause");
}

void SEFunc()
{
    __try
    {
        int* buffer= new int[19];
        buffer[19]=0;
        printf("%d",buffer[19]);
        delete buffer;
    }
    __finally
    {
        printf( "In finally\n" );
    }
}

void trans_func( unsigned int u, EXCEPTION_POINTERS* pExp )
{
    printf( "In trans_func.\n" );
    throw SE_Exception();
}

1 个答案:

答案 0 :(得分:0)

trans_func只会被调用以处理结构化异常。

但是您的代码似乎没有触发SEH异常:

int* buffer= new int[19];
buffer[19]=0;
printf("%d",buffer[19]);
delete buffer;

也许你应该尝试一些更残酷的东西:

volatile int *pInt = 0x00000000;
*pInt = 20;

该示例直接取自MSDN