locked
Possible to catch, wrap and rethrow COMException globally? RRS feed

  • Question

  • I have a number of custom HRESULT error codes I am returning from a COM object to C# code.  In each handler, I have to catch the COMException and compare the ErrorCode member.

    Is there a "global" way I can catch, wrap and rethrow the COMException into a more friendly exception class of my own which the user would catch instead of the COMException directly?

    ...Matt

    Tuesday, September 18, 2012 3:24 PM

Answers

  • No - You'd need to handle this on each exception path.

    That being said, you could write a static utility function that used a lambda to simplify this.  For example, say you have a method like so:

    static T RewrapComException<T>(Func<T> fun)
    {
        try
        {
            fun();
        }
        catch(ComException e)
        {
             throw new MyExceptionWrapper(e);
        }
    }
    

    You could then change a method like so:

    public int Foo(string bar)
    {
        // Some method content
        if (bar == "baz")
            return 42 * MethodThatMightThrow();
        else
            return 59;
    }

    Into this:

    public int Foo(string bar)
    {
      return RewrapComException( () =>
      {  
        // Some method content
        if (bar == "baz")
            return 42 * MethodThatMightThrow();
        else
            return 59;
      });
    }
    

    At least it simplifies the code you have to write vs. the same try/catch logic everywhere...


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Proposed as answer by Mike Feng Wednesday, September 19, 2012 10:43 AM
    • Marked as answer by Matt Houser Wednesday, September 19, 2012 2:15 PM
    Tuesday, September 18, 2012 3:38 PM