3 ms·
It’s funny that they use that awful pyramid-of-doom error handling style in a lot of the public documentation. The correct way is to have an “Error:” label at
by marcoperaza 7y ago
It’s funny that they use that awful pyramid-of-doom error handling style in a lot of the public documentation.
The correct way is to have an “Error:” label at the end of the function before all the cleanup code. After calling any function that can return an error code, you check the error code and “goto Error” if necessary. You can encapsulate that whole logic in a macro so you just call something like CHK(hr) anytime you have an error code to check. CHK being defined as something like “if(FAILED(hr)) goto Error;”. This is how error handling for non-trivial functions is done in any serious C code, regardless of the platform. One common pattern is actually to just put the entire line of code inside the macro, so your code would look like CHK(hr = AWin32Function(param1, param2)). You can get real cute and even have the macro assign hr for you, so you can drop the “hr =“ from your code.
I worked on Windows at Microsoft and with very few exceptions, the only time I saw the pyramid-of-doom was in the public documentation. I wonder if was just bowing to the irrational hostility some people have to any use of goto, even though this is a highly structured pattern that should be uniform across your codebase, the opposite of unstructured, ad-hoc uses of goto that are the actual problem.
- userbinator 7y agoTrue, the error handling could be better, but my main point was really to say that much of that code should not even be necessary; the majority of those calls are really just doing the equivalent of setting a field in a structure in the old way. Furthermore, because it's a function call and "could" fail, "best" (more like dogmatic) practice dictates that the return values must be checked, despite the fact that failure means something was really wrong (like the hardware failing) and there's no way to recover from that, and you can argue that point as much as you like but your corporate-drone manager isn't going to care, only about whether you're "following the standards" and his precious metrics that are just as uncaring. (That's a rant for another day.) On the other hand, no one argues whether you need to check for errors when using assignment statements. Doing it the old way is so much simpler and avoids the whole aforementioned argument issue around pointless error-checking.
- marcoperaza 7y agoYou should always check the return value for an error, no matter what. I would not suggest otherwise. Whatever the source of the failure, you want to explicitly fail in a defined way rather than have your application behave in unexpected ways, potentially destroying user data or otherwise misbehaving.