2012-06-02 106 views
3

我试图捕获在C#Windows窗体应用程序中的所有无关例外。我已将以下代码添加到Program.cs文件中,但未捕获到异常,我收到异常,例如NullReferenceException。 我在做什么错?无法捕获在Winforms中的未处理的异常

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调试运行时,我不能赶上Exception.I知道调试是错误removal.Should我运行程序在构建模式下捕获异常?

+0

邮政编码,实际上重现了问题。 –

回答

2

尝试禁用VS中的异常捕获,因为它似乎在它到达处理程序之前捕获异常。

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

0

你订阅只事件提供了检查异常的一种手段;它们并不意味着允许你抑制或从异常中恢复。

AppDomain.UnhandledException

此事件提供未捕获异常的通知。它允许应用程序在系统默认处理程序向用户报告异常并终止应用程序之前记录有关异常的信息。

如果您想在记录日志后从异常中恢复,则需要在代码中使用try-catch块。