簡體   English   中英

捕獲 C# winform 應用程序中的所有異常

[英]Catch all exception in C# winform application

在 C# winform 桌面應用程序中,我試圖捕獲所有可能出現在代碼中的異常,我已經嘗試過:

  using System;
    using System.Threading;
    using System.Windows.Forms;

    namespace Controller
    {
        static class Program
        {
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                Application.Run(new Form1());
            }

            static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
            {
                MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
            }

            static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");           
            }
        }
    }

我在設備管理器中通過附加“COM6”和沒有串行端口的表單關閉事件來測試它,但我只看到 Visual Studio An exception of type 'System.InvalidOperationException' occurred in System.dll but was not handled in user code報告中An exception of type 'System.InvalidOperationException' occurred in System.dll but was not handled in user code

如何為 winform 應用程序收集錯誤數據

這其實並不難做到。
我建議將處理異常的任何代碼放入主窗體中,以保持program.cs盡可能干凈。

首先在你的Program.cs放這個

static class Program
{
    public static Form MainForm = null;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.ThreadException += Application_ThreadException;
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        MainForm = new Form1();
        Application.Run(MainForm);
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        ((Form1)MainForm).Application_ThreadException(sender, e);
    }
}

然后在你的主表單中放這個

    public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        // All unhandled exceptions will end up here, so do what you need here

        // log the error
        // show the error
        // shut the application down if needed
        // ROLLBACK database changes 
        // and so on...
    }

您可以使用 try-catch 來捕獲所有方法中的異常。 在 catch 中,您可以記錄異常的原因。

try
{
   // Your code that might throw an error
}
catch( Exception e )
{
   // What you want to do when the error is thrown
   Logger.WriteException(e);
}

我更喜歡編寫一個靜態類 'Logger' 和 'WriteException' 方法來將異常記錄到文本文件中。

public static class Logger
{
    public static void WriteException(Exception exception)
    {
        string filePath = @"D:\Error.txt";

        using (StreamWriter logWriter = new StreamWriter(filePath, true))
        {
            logWriter.WriteLine("Message :" + exception.Message + "<br/>" + Environment.NewLine + "StackTrace :" + exception.StackTrace +
               "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            logWriter.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
        }
    }
}

有多種錯誤記錄方法可用,您可以使用適合您的應用程序的一種。 您可以使用 EventLog、Microsoft Logger 等。

在應用程序的一個點上捕獲所有錯誤不是最佳實踐。 我建議您確定代碼可能失敗的地方,並使用 try/catch 塊來捕獲特定的錯誤組。 通過這種方式,您可以更好地控制您的應用程序,並且可以更好地識別代碼的弱點。 例如:

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {

    try{
      //Put here your code
    }
    catch{
    }
}

一個通用的“異常”肯定不能幫助你或用戶識別應用程序中可能的錯誤

暫無
暫無

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

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