Click here to Skip to main content
Licence CPOL
First Posted 18 Sep 2005
Views 54,278
Downloads 392
Bookmarked 32 times

HRESULT Error Check Simplifier

By | 12 Jun 2011 | Article
Exception based error check that automates the FAILED() comparison.

Introduction

It is boring to have to write a lot of ifs only to check for failures. At the same time, it is important to take care of every error that can happen in the code. The class described in this article just makes it easy to throw an exception every time a failure is returned from another function. This way you can do only what you have to do in the code and unify error handling.

With a little help from my colleagues from CP, here is an updated version with some traits for a no-throw version, and a new method to show a textual version for the HRESULT error:

template<bool ThrowException>
struct HResultChecker
{
    static void Check(HRESULT hr);
};

template<> struct HResultChecker<false>
{
    static void Check(HRESULT hr) 
    {
        hr;
    }
};

template<> struct HResultChecker<true>
{
    static void Check(HRESULT hr)
    { 
        if( FAILED(hr) ) 
            AtlThrow(hr);
    }
};


/**
* Use this class instead HRESULT in order to the assignement operator be 
* tested. In case of failure, the funcion AtlThrow() will be called.
*
* @sa AtlThrow(), CAtlException.
*/
template<bool ThrowException>
class HResultT
{
public:
    /// Test the HRESULT in the constructor.
    HResultT(HRESULT hr = S_OK)    { Assign(hr); }

    /// Test failure of the received hr. If FAILED(hr), the function 
    /// AtlThrow() will be called.
    HResultT &operator = (HRESULT hr)
    {
        Assign(hr);
        return *this;
    }

    /** 
    * Retrieves the error desription of the HRESULT member.
    * @return string message for the HRESULT.
    *
    * @author ddarko (comment from CodeProject)
    * @date 2005-09
    */
    LPCTSTR ErrorMessage()
    {
        // a lot of code
    }

    /// Extractor of the stored HRESULT.
    operator HRESULT () { return m_hr; }

private:
    void Assign(HRESULT hr) // throw( CAtlException )
    {
        HResultChecker<ThrowException>::Check(m_hr = hr);
    }

    HRESULT m_hr; // the stored HRESULT
    std::basic_string<TCHAR> m_desc; // error description
};

/// Throw exception version.
typedef HResultT<true> HResult;

// No-Throw exception version.
typedef HResultT<false> HResultSafe;

Using the code

The use is very straightforward. You can catch the exceptions inside the function or pass it to the callee:

/**
Using HResult inside the funcion
*/
void function()
{
   HResult hr;

   try
   {
      hr = MakeSomething();
      hr = MakeSomethingElse();
      hr = MakeTheFinalSomething();
   }
   catch(CAtlException& e)
   {
      cout << "wow! Error " << e.m_hr << ": " << e.ErrorMessage() << "\n";
   }
}

/**
Using HResult bypassing the exception
*/
void Class::Method() throw ( CAtlException )
{
   HResult hr = MakeSomething();
   hr = MakeSomethingElse();
   hr = MakeTheFinalSomething();
}

Points of interest

Maybe before using the class above, you would to like to learn about CAtlException, AtlThrow(), and FormatMessage(). Very interesting stuff for exception based error handling.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Wanderley Caloni

Web Developer

Brazil Brazil

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralTrait classes for exception vs. manual check. PinmemberCoffeeBuzz6:40 3 May '08  
GeneralRe: Trait classes for exception vs. manual check. PinmemberWanderley Caloni1:18 5 May '08  
GeneralRe: Trait classes for exception vs. manual check. PinmemberYiannis Spyridakis7:12 11 Jun '11  
GeneralRe: Trait classes for exception vs. manual check. PinmemberWanderley Caloni9:19 12 Jun '11  
GeneralRe: Trait classes for exception vs. manual check. PinmemberYiannis Spyridakis2:27 13 Jun '11  
GeneralError description PinmemberDarko@Hot3:40 5 Mar '07  
GeneralRe: Error description PinmemberWanderley Caloni6:05 5 Mar '07  
GeneralRe: Error description PinmemberDarko@Hot6:46 5 Mar '07  
GeneralDid you know the trick ... PinmemberStephan Pilz2:29 19 Sep '05  
GeneralRe: Did you know the trick ... PinmemberWanderley Caloni3:39 19 Sep '05  
Generalit works but not perfect PinmemberHeartFriend15:46 18 Sep '05  
GeneralRe: it works but not perfect PinmemberWanderley Caloni17:33 18 Sep '05  
GeneralRe: it works but not perfect PinmemberWanderley Caloni18:03 18 Sep '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 12 Jun 2011
Article Copyright 2005 by Wanderley Caloni
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid