views:

34

answers:

2

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 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.

+1  A: 

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

anno
+1  A: 

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.

Hans Passant