【问题标题】:Catch ALL errors not just individual buttons [duplicate]捕获所有错误,而不仅仅是单个按钮[重复]
【发布时间】:2014-01-14 12:29:12
【问题描述】:

我想要一个适用于所有功能的通用捕获所有错误。现在,我尝试捕获特定事件的每个单独按钮单击。我需要为我的整个程序捕获所有错误,其中包括所有可以捕获我可能错过的任何单个异常的按钮单击。有人可以指出我正确的方向

我当前的代码:

private void Show_btn_Click(object sender, EventArgs e)
{
  try
 {
   //do something
 }
 catch (Exception error)
 {
    outputLOG.Append(error.ToString());
 {
}

private void Submit_btn_Click(object sender, EventArgs e)
{
  try
 {
   //do something
 }
 catch (Exception error)
 {
    outputLOG.Append(error.ToString());
 }
}

目标:我想捕获所有按钮,以防我错过个别异常

编辑:我正在使用 winforms

【问题讨论】:

标签: c# winforms error-handling


【解决方案1】:

在进入应用程序的第一个表单之前添加这些行(通常在 program.cs 的 main 方法中)

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

private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    string msg = e.Exception.Message;
    if (e.Exception.InnerException != null)
    {
        msg = msg + "\r\nPrevious error:" + e.Exception.InnerException.Message;
    }
    msg = msg + "\r\n\r\nDo you wish to continue with the application?";
    DialogResult dr = MessageBox.Show(msg, "Exception", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (dr == DialogResult.No) Application.Exit();
}

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Exception ex = e.ExceptionObject as Exception;
    if (ex != null)
    {
        string msg = ex.Message;
        if (ex.InnerException != null)
        {
            msg = msg + "\r\nPrevious error :" + ex.InnerException.Message;
        }
        msg = msg + "\r\n\r\nIt is not possible to continue. Contact support service!";
        MessageBox.Show(msg, "Fatal Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

【讨论】:

  • 我收到此错误:SetUnhandledExceptionMode 是一种方法并被用作类型
  • 在该行之前可能存在某种错误。请参阅MSDN reference。我不知道为什么编译器会考虑类型
猜你喜欢
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2022-12-10
  • 2015-08-18
  • 2021-06-24
相关资源
最近更新 更多