c#UserControl构造函数don';t按预期抛出异常
这是Program.cs中我的WinForm解决方案入口点:c#UserControl构造函数don';t按预期抛出异常,c#,.net,constructor,exception-handling,user-controls,C#,.net,Constructor,Exception Handling,User Controls,这是Program.cs中我的WinForm解决方案入口点: try { Application.Run(new MainForm()); } catch (Exception e) { Log.error(e.ToString()); ErrorHandlerForm abend = new ErrorHandlerForm(e); abend.ShowDialog(); } 它工作正常,我的解决方案中抛出的每个异常都得到了优雅的处理 但今天我发现了一个问题: 我的程序不会捕
try
{
Application.Run(new MainForm());
}
catch (Exception e)
{
Log.error(e.ToString());
ErrorHandlerForm abend = new ErrorHandlerForm(e);
abend.ShowDialog();
}
它工作正常,我的解决方案中抛出的每个异常都得到了优雅的处理
但今天我发现了一个问题:
我的程序不会捕获UserControls构造函数中发生的异常
它只是在丑陋的系统提示下崩溃到windows(或者如果我处于调试模式,它会在VisualStudio中显示错误)
我不理解这种行为,也不知道如何修复它,我想在catch块中捕获这些异常。答案试图解释潜在的问题
只需在主方法中添加以下行:
//Add the event handler for handling all unhandled UI thread exceptions to the event Application_ThreadException
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
并使用此方法处理异常:
/// <summary>
/// Handles all unhandled UI thread exceptions
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Threading.ThreadExceptionEventArgs"/> instance containing the event data.</param>
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
//handle e.Exception here
}
其中CurrentDomain\u UnhandledException是您的异常处理程序方法。在调试模式下,在Visual studio中会出现什么错误?
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);