无法捕捉未处理的异常中的WinForms异常、未处理、WinForms

2023-09-06 17:36:07 作者:君未叹沉香

我试图捕捉在C#的Windows所有unhanded例外窗体应用程序。我已经添加了以下code到的Program.cs 文件,但异常未被捕获,我得到的异常,如的NullReferenceException 。 我究竟做错了什么?

I'm trying to capture all unhanded Exceptions in a C# Windows Forms Application. I have added the following code to the Program.cs file but the exceptions are not captured, I get Exceptions such as NullReferenceException. What am I doing wrong?

static void Main()
{ 
    System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandedException);
    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
    var form = new MainForm();
    form.ShowDialog();
}

private static void HandleUnhandledException(Object o)
{
    // TODO: Log it!
    Exception e = o as Exception;
    if (e != null)
    {
    }
}

private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
    HandleUnhandledException(e.ExceptionObject);
}

private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
    HandleUnhandledException(e.Exception);
}

编辑:我能捕捉到的异常时,程序的Visual Studio之外的外部运行,但是从Visual Studio debuging当我不能赶上Exception.I知道调试是错误removal.Should我运行程序在建立模式来捕获异常?

推荐答案

尝试禁用异常捕获的VS,因为它似乎前,先要到您的处理程序来捕捉异常。

Try disabling exception catching in VS, as it seems to catch the exception before it gets to your handlers.

调试>例外...>取消选中用户未处理的公共语言运行库异常。

Debug > Exceptions... > Uncheck User-unhandled for Common Language Runtime Exceptions.

 
精彩推荐