c++ - 将 GetLastError() 变成异常

标签 c++ exception error-handling

我有一个 Visual Studio 2008 C++ 项目,它在出现异常 错误时使用 Win32Exception 类。 Win32Exception 类如下所示:

/// defines an exception based on Win32 error codes. The what() function will
/// return a formatted string returned from FormatMessage()
class Win32Exception : public std::runtime_error
{
public:
    Win32Exception() : std::runtime_error( ErrorMessage( &error_code_ ) )
    {
    };

    virtual ~Win32Exception() { };

    /// return the actual error code
    DWORD ErrorCode() const throw() { return error_code_; };

private:

    static std::string ErrorMessage( DWORD* error_code )
    {
        *error_code = ::GetLastError();

        std::string error_messageA;
        wchar_t* error_messageW = NULL;
        DWORD len = ::FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | 
                                      FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                      FORMAT_MESSAGE_IGNORE_INSERTS,
                                      NULL,
                                      *error_code,
                                      MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
                                      reinterpret_cast< LPWSTR >( &error_messageW ),
                                      0,
                                      NULL );
        if( NULL != error_messageW )
        {
            // this may generate a C4244 warning. It is safe to ignore.
            std::copy( error_messageW, 
                       error_messageW + len, 
                       std::back_inserter( error_messageA ) );
            ::LocalFree( error_messageW );
        }
        return error_messageA;
    };

    /// error code returned by GetLastError()
    DWORD error_code_;

}; // class Win32Exception

该类在使用它的情况下运行良好。我想知道是否有任何我应该注意的明显的失败案例。欢迎提出任何其他问题、注意事项或一般性改进建议。

请注意,boost 库不是此代码的选项。

最佳答案

请注意,如果 back_inserter 导致抛出 std::bad_alloc,则 FormatMessage 中分配的内存将泄漏。

关于c++ - 将 GetLastError() 变成异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475157/

相关文章:

c++ - 使用 QMovie 在 GIF 动画和 Qt 中的信号/槽之间切换

c++ - 编译器在构造函数中计算出的成员偏移不正确

c# - 如果我在 catch 中添加一个只有 Debugger.Break() 的 try-catch block

error-handling - “NSError”无法转换为 'AutoreleasingUnsafePointer<NSError?>'

python - 股票数据请求被拒绝后继续查询Yahoo Finance

c++ - 如何编写可以在 msdos 上运行的 C++ 控制台 exe?

c++ - 如何解决错误 : Cannot convert from 'OSamp::Weapon' to 'OSamp::Weapon' in C++ CLR

reactjs - react ,如何调试(axios)404错误?

java - 了解 Mockito 验证背后的语义

python - 获取完整的异常类型/消息和堆栈跟踪