Karsten
Karsten

Reputation: 8144

.Net com server catch unhandled exception

I've created a Com server in C#. The project type is class library. Is there a way to get en event for unhandled exceptions in my code? I've tried AppDomain.CurrentDomain.UnhandledException without any luck

Upvotes: 1

Views: 313

Answers (2)

to StackOverflow
to StackOverflow

Reputation: 124696

Because this isn't possible as described in Hans Passant's answer, and because useful information such as the Stack Trace is lost when an Exception is converted to a COM HRESULT, I often use explicit interface implementation to ensure exceptions are logged when my ComVisible library is called from a COM client. A bit of work, but COM interfaces tend to be stable so it's only done once.

E.g.:

[ComVisible(true)]
public interface IMyClass
{
    void MyMethod();
    ...
}

[
ComVisible(true),
ClassInterface(ClassInterfaceType.None)
]
public MyClass : IMyClass
{
    ...

    public MyMethod()
    {
        ... implementation 
    }

    void IMyClass.MyMethod()
    {
        try
        {
            this.MyMethod();
        }
        catch(Exception ex)
        {
            _logger.Log(ex);
            throw;
        }

    }
}

Upvotes: 3

Hans Passant
Hans Passant

Reputation: 941327

Not possible. The COM interop support code in the CLR implements the restriction in COM that exceptions are not allowed to escape from a COM method. Your method will be called with a catch-all exception handler inside the CLR that catches any exception you throw. It gets translated to a COM error code, an HRESULT, the return value of any COM Automation compatible interface method. The value of Exception.HResult. The COM client code uses that value to determine if the method call failed.

You can otherwise use the debugger and make it stop on any exceptions. Debug + Exceptions, tick the Thrown checkbox. The debugger automatically breaks on the 'first chance' exception.

Upvotes: 4

Related Questions