开发者

C# Override try-catch in another function

I am using a dll that I got from the 开发者_开发技巧internet for utilizing a webcam in C#. If it can't find a webcam connected I would like to display something like "Unable to find a camera to use. Please verify that no other applications are using your camera at this time and try again". The problem I am having is the creator of the dll included a try-catch in their dll programming...so my try-catch never see's the exception because a "object referenced not set to an instance of an object" error comes up instead (formatted by a try/catch into a MessageBox). Is there a way I can override the built-in error handling before it displays the message and display my own?


If you're getting "object referenced not set to an instance of an object" (NullReferenceException), then it is likely they didn't actually catch the exception.

If you want to catch that exact case (and let others errors you don't know about and can't handle fall through - the proper way to do exception handling), you can try getting down and dirty with the stack information included with the exception:

class Program
{
    public static void DoSomething()
    {
        string blah = null;
        Console.WriteLine(blah.Length);
    }

    static void Main(string[] args)
    {
        try
        {
            DoSomething();
        }
        catch (NullReferenceException e)
        {
            string methodName = e.TargetSite.Name;
            Console.WriteLine(methodName);

            System.Diagnostics.StackTrace trace =
                new System.Diagnostics.StackTrace(e, true);

            int lineNumber = trace.GetFrame(0).GetFileLineNumber();
            Console.WriteLine(lineNumber);

            if(methodName == "DoSomething" && lineNumber == 13)
            {
                ShowErrorToUser(); // Todo: Implement this
            }
            else
            {
                throw; // Just re-throw the error if you don't know where it came from
            }
        }
    }
}

Edit

Found out in the comments that it really is being caught, and displayed in a message box.

I will leave this answer since it is applicable to a similar situation, but not applicable to this situation. See OscarMK's answer instead.


You cannot override the try-catch block only, but you could override the method and basically do everything the previous method is doing and removing the try-catch block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜