开发者

Suggestions on error handling of Win32 C++ code: AtlThrow vs. STL exceptions

In writing Win32 C++ code, I'd appreciate some hints on how to handle errors of Win32 APIs.

In particular, in case of a failure of a Win32 function call (e.g. MapViewOfFile), is it better to:

  1. use AtlThrowLastWin32

  2. define a Win32Exception class derived from std::exception, with an added HRESULT data member to 开发者_C百科store the HRESULT corresponding to value returned by GetLastError?

In this latter case, I could use the what() method to return a detailed error string (e.g. "MapViewOfFile call failed in MyClass::DoSomething() method.").

What are the pros and cons of 1 vs. 2?

Is there any other better option that I am missing?

As a side note, if I'd like to localize the component I'm developing, how could I localize the exception what() string? I was thinking of building a table mapping the original English string returned by what() into a Unicode localized error string. Could anyone suggest a better approach?

Thanks much for your insights and suggestions.


AtlThrow isn't terribly useful, it throws CAtlException which merely wraps an error code. Having a MapViewOfFile fail is a truly exceptional problem with a low-level error code that doesn't tell you or your user much at all what actually went wrong. Handling the error is almost always impossible, it isn't likely that you can shrug it off and just not use a MMF. You'll have to log the error and terminate your program with a very generic error.

Getting very detailed in your error message is usually wasted effort. "MapViewOfFile call failed in MyClass::DoSomething() method" just doesn't mean anything at all to your user or her support staff. Great for you though, something to trace the error to. But you can easily automate this, without localization trouble, by using the __FILE__ and __LINE__ macros. All that you really need to match the error to the source code.

Keep the error message short and snappy. For Windows errors, you'll want to use FormatMessage() to let Windows generate the message. It will automatically be localized, the message text is standardized and googles well. Deriving from std::exception is okay. Use string resource IDs for custom messages so you can easily localize them. Solves the what() problem too.


You shouldn't use exceptions for error handling. Exceptions are exceptional. For C++ error handling, look at : System error support in C++0x

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜