Infovark Underground

  • news
    • infoblog
    • underground
  • product
  • download
  • buy
  • support
  • about
    • ← Creating Dummy Targets for Configuration Objects
    • Tools: Beyond Compare 3 →

    Handling COM Error Codes

    20 Aug 2008 by Gordon in .NET, Programming / No Comments

    Sometimes COM Objects return a HRESULT that is outside of the bounds of a C#  integer.

    Unfortunately, the only way to correctly handle a COM Exception in .NET is to use the ComException Class. But if the HRESULT isn’t an Int, and the ErrorCode Property on the ComException class is an Int, how are you supposed to ever be able to catch that specific HRESULT?

    Fear not! Here’s how to handle a COM ErrorCode that can’t be converted to an Int (in this example, it’s unsigned)

    try
    1.  {
    2.   _PropertyHandler.Open(filePath, false, dsoFileOpenOptions.dsoOptionDefault);
    3.  }
    4.  catch (COMException comEx)
    5.  {
    6.   if (comEx.ErrorCode == unchecked((int)0x800300FC))
    7.    {
    8.     throw new FileNotFoundException("Could not find file:");
    9.    }
    10.  }

    The magic happens in the ‘unchecked’ statement – which tells the compiler not to perform the overflow-checking context for integral-type arithmetic operations and conversions.

    More on the Unchecked Operator over on MSDN.

    Related posts

    1. Creating Dummy Targets for Configuration Objects
    2. Enums are Ints that Ain’t
    3. Switch By Type in C#
    • Tweet
    • Tags:
    • C#
    • COM
    • exception

    Leave a Comment

    Posting your comment...

    Subscribe to these comments via email

    • Categories

      • .NET (41)
      • AJAX (3)
      • Books (7)
      • HTML (9)
      • Infovark (8)
      • Programming (48)
      • REST (11)
      • SQL (3)
      • Testing (3)
      • Tools (13)
      • UI (3)
      • WCF (11)
      • Web Services (8)
      • WPF (4)
      • XML (4)
    • Archives

    • Get future articles


       

    • Blogroll

      • Ajaxian
      • Anne Van Kesteren
      • Brain.Save()
      • Coding Horror
      • Eric Sink
      • Joel Spolsky
      • John Resig
      • Mark Pilgrim
      • Raymond Chen
      • Scott Hansleman
      • Secret Geek
      • Steve Yegge
      • The Daily WTF
      • The Database Programmer
    • Meta

      • Log in
      • Entries RSS
      • Comments RSS
      • WordPress.org
  • Site map

    • News
    • Product
    • Download
    • Buy
    • Support
    • About
  • Recent Posts

    • Review: Brownfield Application Development in .NET
    • Using Modal Dialogs with a Splash Screen in WPF
    • Highlighting query terms in a WPF TextBlock
    • Getting XAML Hyperlink text to wrap
    • How to format the XAML Hyperlink NavigateUri
  • Twitter

    Copyright 2011 Infovark, Inc. All rights reserved.