我有一个 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 库不是此代码的选项。
最佳答案
- 这已经被很多人做过了,包括你的
具有讽刺意味的是,您的代码并不是异常安全的。
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 ); }
请注意,如果 back_inserter
导致抛出 std::bad_alloc
,则 FormatMessage
中分配的内存将泄漏。
关于c++ - 将 GetLastError() 变成异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4475157/