簡體   English   中英

僅當從Visual Studio啟動時,Program.cs中的Try-Catch才起作用

[英]Try-Catch in Program.cs only works when started from visual studio

我試圖為未完成的任務寫一個小崩潰記者。 在VS中啟動我的應用程序時,這非常完美。 但是,一旦我嘗試啟動.exe,它只會向我顯示標准的“存在未捕獲的錯誤”-從Windows啟動。 不,崩潰的不是崩潰報告器。

這是我在Program.cs中的代碼

        try
        {
            Application.Run(new TestServer());
        }
        catch (Exception e)
        {
            Application.Run(new CrashReporter(e.StackTrace.ToString()));
        }
    }

這是因為您使用調試器。 Winforms會檢測到此情況,並禁用Application.ThreadException的事件處理程序。 這很重要,它使您可以調試異常。 為了使catch子句在沒有調試器的情況下工作,您必須在Run()調用之前將此語句添加到Main()方法中:

   Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

現在,改為為AppDomain.Current.UnhandledException編寫事件處理程序確實更有意義,您還將收到有關工作線程中未處理異常的通知。

代替此,您可以處理以下事件(這是處理未處理的應用程序異常的首選方式):

AppDomain.CurrentDomain.UnhandledException += (sender, e) => 
{  
    Application.Run(new CrashReporter(e.StackTrace.ToString())); 
}
Application.Run(new TestServer());

您是否在64位操作系統上運行? 這聽起來像是Hans Passant 在這里回答的問題。

調試可能會吞噬64位CLR中Form構造和Forms_Load上的錯誤...

您確定這件事可行嗎? 我的意思是,此策略以前對您有用嗎?

我使用(並建議的方式)這種方式來全局捕獲未處理的異常:

    AppDomain.CurrentDomain.UnhandledException +=
            new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//then start the main form...
Application.Run(new TestServer());

這是文檔http://msdn.microsoft.com/zh-cn/library/system.appdomain.unhandledexception.aspx

CrashReporter導致了它。 catch語句中未捕獲的異常將導致未捕獲的異常。 您需要在捕獲中再次嘗試/捕獲,然后再回退。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM