如何处理所有的错误,包括内部C库错误,均匀 [英] How to handle all errors, including internal C library errors, uniformly

查看:1102
本文介绍了如何处理所有的错误,包括内部C库错误,均匀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要优雅地处理所有的内部错误,没有程序终止。

I wanted to handle all internal errors gracefully, without program termination.

随着讨论的这里,使用< STRONG> _set_se_translator 捕捉除以零错误。

As discussed here, using _set_se_translator catches divide-by-zero errors.

不过,这并不赶上,例如,C运行时库错误的 -1073740777(0xc0000417)的,可以通过格式字符串引起的的printf 具有百分号他们不应该。 (这只是一个例子,我们当然应该检查这些字符串)。为了处理这些, _set_invalid_parameter_handler 是必要的。

But it does not catch, for example, C runtime library error -1073740777 (0xc0000417), which can be caused by format strings for printf which have the percent sign where they shouldn't. (That is just an example; of course we should check for such strings). To handle these, _set_invalid_parameter_handler is needed.

有上市的<关于其他十这样的处理程序href=\"http://stackoverflow.com/questions/82483/how-to-catch-all-exceptions-crashes-in-a-net-app\">here.

另外,这个人会赶上未捕获的C ++异常:的 SetUnhandledExceptionFilter 。因此,可以一起在 _ 设置的_ ... 函数中使用。 (约在2008年MSVC使用它的文章。)

In addition, this one will catch uncaught C++ exceptions: SetUnhandledExceptionFilter. Thus, it can be used together with the _set_ ... functions. (An article about using it in MSVC 2008.)

我要赶任何和所有的错误,所以我可以处理它们(伐木,抛出一个现代化的C ++标准异常并返回一个特定应用程序的错误code)。是否有抓住一切单个处理程序?

I want to catch any and all errors so I can handle them (by logging, throwing a modern C++ standard exception and returning an application-specific error code). Is there a single handler that catches everything?

这也是在见<一href=\"http://stackoverflow.com/questions/82483/how-to-catch-all-exceptions-crashes-in-a-net-app\">StackOverflow.

我使用Visual Studio 2008。

I am using Visual Studio 2008.

推荐答案

有没有通用的处理程序。你需要安装每一个。我用这样的:

There is no universal handler. You need to install each one. I have used something like this:

///////////////////////////////////////////////////////////////////////////
template<class K, class V>
class MapInitializer
{
    std::map<K,V> m;
public:
    operator std::map<K,V>() const 
    { 
        return m; 
    }

    MapInitializer& Add( const K& k, const V& v )
    {
        m[ k ] = v;
        return *this;
    }
};

///////////////////////////////////////////////////////////////////////////
struct StructuredException : std::exception
{
    const char *const msg;
    StructuredException( const char* const msg_ ) : msg( msg_ ) {}
    virtual const char* what() const { return msg; }
};

///////////////////////////////////////////////////////////////////////////
class ExceptionHandlerInstaller
{
public:
    ExceptionHandlerInstaller()
        : m_oldTerminateHandler( std::set_terminate( TerminateHandler ) )
        , m_oldUnexpectedHandler( std::set_unexpected( UnexpectedHandler ) )
        , m_oldSEHandler( _set_se_translator( SEHandler ) )
    {}

    ~ExceptionHandlerInstaller() 
    { 
        std::set_terminate( m_oldTerminateHandler );
        std::set_unexpected( m_oldUnexpectedHandler );
        _set_se_translator( m_oldSEHandler );
    }

private:
    static void TerminateHandler() 
    { 
        TRACE( "\n\n**** terminate handler called! ****\n\n" );
    }

    static void UnexpectedHandler() 
    { 
        TRACE( "\n\n**** unexpected exception handler called! ****\n\n" );
    }

    static void SEHandler( const unsigned code, EXCEPTION_POINTERS* )
    {
        SEMsgMap::const_iterator it = m_seMsgMap.find( code );
        throw StructuredException( it != m_seMsgMap.end() 
            ? it->second 
            : "Structured exception translated to C++ exception." );
    }

    const std::terminate_handler  m_oldTerminateHandler;
    const std::unexpected_handler m_oldUnexpectedHandler;
    const _se_translator_function m_oldSEHandler;

    typedef std::map<unsigned, const char*> SEMsgMap;
    static const SEMsgMap m_seMsgMap;
};

///////////////////////////////////////////////////////////////////////////
// Message map for structured exceptions copied from the MS help file
///////////////////////////////////////////////////////////////////////////
const ExceptionHandlerInstaller::SEMsgMap ExceptionHandlerInstaller::m_seMsgMap 
    = MapInitializer<ExceptionHandlerInstaller::SEMsgMap::key_type, 
                     ExceptionHandlerInstaller::SEMsgMap::mapped_type>()
    .Add( EXCEPTION_ACCESS_VIOLATION,         "The thread attempts to read from or write to a virtual address for which it does not have access. This value is defined as STATUS_ACCESS_VIOLATION." )
    .Add( EXCEPTION_ARRAY_BOUNDS_EXCEEDED,    "The thread attempts to access an array element that is out of bounds, and the underlying hardware supports bounds checking. This value is defined as STATUS_ARRAY_BOUNDS_EXCEEDED." )
    .Add( EXCEPTION_BREAKPOINT,               "A breakpoint is encountered. This value is defined as STATUS_BREAKPOINT." )
    .Add( EXCEPTION_DATATYPE_MISALIGNMENT,    "The thread attempts to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries, 32-bit values on 4-byte boundaries, and so on. This value is defined as STATUS_DATATYPE_MISALIGNMENT." )
    .Add( EXCEPTION_FLT_DENORMAL_OPERAND,     "One of the operands in a floating point operation is denormal. A denormal value is one that is too small to represent as a standard floating point value. This value is defined as STATUS_FLOAT_DENORMAL_OPERAND." )
    .Add( EXCEPTION_FLT_DIVIDE_BY_ZERO,       "The thread attempts to divide a floating point value by a floating point divisor of 0 (zero). This value is defined as STATUS_FLOAT_DIVIDE_BY_ZERO." )
    .Add( EXCEPTION_FLT_INEXACT_RESULT,       "The result of a floating point operation cannot be represented exactly as a decimal fraction. This value is defined as STATUS_FLOAT_INEXACT_RESULT." )
    .Add( EXCEPTION_FLT_INVALID_OPERATION,    "A floatin point exception that is not included in this list. This value is defined as STATUS_FLOAT_INVALID_OPERATION." )
    .Add( EXCEPTION_FLT_OVERFLOW,             "The exponent of a floating point operation is greater than the magnitude allowed by the corresponding type. This value is defined as STATUS_FLOAT_OVERFLOW." )
    .Add( EXCEPTION_FLT_STACK_CHECK,          "The stack has overflowed or underflowed, because of a floating point operation. This value is defined as STATUS_FLOAT_STACK_CHECK." )
    .Add( EXCEPTION_FLT_UNDERFLOW,            "The exponent of a floating point operation is less than the magnitude allowed by the corresponding type. This value is defined as STATUS_FLOAT_UNDERFLOW." )
    .Add( EXCEPTION_GUARD_PAGE,               "The thread accessed memory allocated with the PAGE_GUARD modifier. This value is defined as STATUS_GUARD_PAGE_VIOLATION." )
    .Add( EXCEPTION_ILLEGAL_INSTRUCTION,      "The thread tries to execute an invalid instruction. This value is defined as STATUS_ILLEGAL_INSTRUCTION." )
    .Add( EXCEPTION_IN_PAGE_ERROR,            "The thread tries to access a page that is not present, and the system is unable to load the page. For example, this exception might occur if a network connection is lost while running a program over a network. This value is defined as STATUS_IN_PAGE_ERROR." )
    .Add( EXCEPTION_INT_DIVIDE_BY_ZERO,       "The thread attempts to divide an integer value by an integer divisor of 0 (zero). This value is defined as STATUS_INTEGER_DIVIDE_BY_ZERO." )
    .Add( EXCEPTION_INT_OVERFLOW,             "The result of an integer operation causes a carry out of the most significant bit of the result. This value is defined as STATUS_INTEGER_OVERFLOW." )
    .Add( EXCEPTION_INVALID_DISPOSITION,      "An exception handler returns an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception. This value is defined as STATUS_INVALID_DISPOSITION." )
    .Add( EXCEPTION_INVALID_HANDLE,           "The thread used a handle to a kernel object that was invalid (probably because it had been closed.) This value is defined as STATUS_INVALID_HANDLE." )
    .Add( EXCEPTION_NONCONTINUABLE_EXCEPTION, "The thread attempts to continue execution after a non-continuable exception occurs. This value is defined as STATUS_NONCONTINUABLE_EXCEPTION." )
    .Add( EXCEPTION_PRIV_INSTRUCTION,         "The thread attempts to execute an instruction with an operation that is not allowed in the current computer mode. This value is defined as STATUS_PRIVILEGED_INSTRUCTION." )
    .Add( EXCEPTION_SINGLE_STEP,              "A trace trap or other single instruction mechanism signals that one instruction is executed. This value is defined as STATUS_SINGLE_STEP." )
    .Add( EXCEPTION_STACK_OVERFLOW,           "The thread uses up its stack. This value is defined as STATUS_STACK_OVERFLOW." );

然后在主或应用初始化,我这样做:

Then in main or app init, I do this:

BOOL CMyApp::InitInstance()
{
    ExceptionHandlerInstaller ehi;
    // ...
}

请注意,这个转换结构化异常常规异常,但处理终止(这被调用,例如,当一个无抛出()函数抛出异常),只需打印错误信息。要使用一个处理程序为所有不同类型的错误,这就是为什么他们不提供它这是极不可能的。

Note that this translates structured exceptions to regular exceptions but handles terminate (which gets called, e.g., when a nothrow() function throws an exception) by simply printing an error message. It is highly unlikely that you want to use a single handler for all different types of errors, which is why they don't provide it.

这篇关于如何处理所有的错误,包括内部C库错误,均匀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆