Click here to Skip to main content
15,867,308 members
Articles / Desktop Programming / ATL

HRESULT Error Check Simplifier

Rate me:
Please Sign up or sign in to vote.
4.19/5 (13 votes)
12 Jun 2011CPOL 94.2K   535   33   16
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:

C++
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:

C++
/**
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)


Written By
Technical Lead Intelitrader
Brazil Brazil
Wanderley Caloni
Backend Specialist
Location: São Paulo, Brazil
Email: wanderley.caloni@gmail.com
Skills
C, C++, Assembly, Windows, x86, Reverse Engineering, Cryptography, Tech/Art Writing, Debugging, Git, SQL

Experience
Intelitrader, 2015 - current (Tech Lead)
Market Data System
DataHub System
Finantial Market Vendor Projects
BitForge, 2015 - current (Owner Developer)
Appliance ATM System Security
Information Security Product Maintenance
Minor projects and skills
Communication API with HID USB devices
Windows Phone and Android user interfaces programming
Boost.Asio Winsock bug
Hidapi issue with IO pending
UOL Diveo Broker, 2012 - 2015 (Backend Developer)
Financial Market Risk System (Stock Broker)
HUB Network API Development and Maintenance
Scua Information Security, 2008 - 2012 (Security Developer)
Information Security Product Maintenance
Disk Cryptography
Team Coordination
Minor projects and skills
Hardware inventory using WMI/SMBIOS
Software inventory using Windows Registry
PrintScreen protection using COM interfaces
Windows Event Log using device driver
User/Kernel communication using DeviceIoControl API
VNC like development
PsExec like development
Documents print control using regex (boost) and shell hook
User policies management using Windows Registry and API hooks
Database migration from CTree to SQL using OLE classes
Windows authentication using DCOM service, custom GINA and Credential Provider (Windows Vista)
Database synchronization using DCOM service
Linux maintenance bootable CD, bash scripts and cryptography tools
USB Cryptography (pen drives)
Crash dump analysis using Windbg
System account process execution using COM service
MBR (Master Boot Record) customization analysing BIOS features
Blowfish and SHA-1 development in 16 bits assembly (x86)
Audit driver using shared memory between user and kernel events
Open Communications Security, 2005 - 2008 (Security Specialist)
Reverse Engineering (Trojan Analysis)
API Hooking
Antidebugging Solution
Code Ofusc

Comments and Discussions

 
GeneralMy vote of 5 Pin
KarstenK20-Nov-13 0:25
mveKarstenK20-Nov-13 0:25 
GeneralMy vote of 5 Pin
OAlpha28-Sep-13 15:25
OAlpha28-Sep-13 15:25 
GeneralRe: My vote of 5 Pin
Wanderley Caloni20-Apr-15 2:49
professionalWanderley Caloni20-Apr-15 2:49 
GeneralTrait classes for exception vs. manual check. Pin
CoffeeBuzz3-May-08 6:40
CoffeeBuzz3-May-08 6:40 
GeneralRe: Trait classes for exception vs. manual check. Pin
Wanderley Caloni5-May-08 1:18
professionalWanderley Caloni5-May-08 1:18 
GeneralRe: Trait classes for exception vs. manual check. Pin
Yiannis Spyridakis11-Jun-11 7:12
Yiannis Spyridakis11-Jun-11 7:12 
GeneralRe: Trait classes for exception vs. manual check. Pin
Wanderley Caloni12-Jun-11 9:19
professionalWanderley Caloni12-Jun-11 9:19 
GeneralRe: Trait classes for exception vs. manual check. Pin
Yiannis Spyridakis13-Jun-11 2:27
Yiannis Spyridakis13-Jun-11 2:27 
GeneralError description Pin
Darko@Hot5-Mar-07 3:40
Darko@Hot5-Mar-07 3:40 
GeneralRe: Error description Pin
Wanderley Caloni5-Mar-07 6:05
professionalWanderley Caloni5-Mar-07 6:05 
GeneralRe: Error description Pin
Darko@Hot5-Mar-07 6:46
Darko@Hot5-Mar-07 6:46 
GeneralDid you know the trick ... Pin
Stephan Pilz19-Sep-05 2:29
Stephan Pilz19-Sep-05 2:29 
GeneralRe: Did you know the trick ... Pin
Wanderley Caloni19-Sep-05 3:39
professionalWanderley Caloni19-Sep-05 3:39 
Generalit works but not perfect Pin
HeartFriend18-Sep-05 15:46
HeartFriend18-Sep-05 15:46 
GeneralRe: it works but not perfect Pin
Wanderley Caloni18-Sep-05 17:33
professionalWanderley Caloni18-Sep-05 17:33 
GeneralRe: it works but not perfect Pin
Wanderley Caloni18-Sep-05 18:03
professionalWanderley Caloni18-Sep-05 18:03 

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

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