在运行时捕获所有异常? C#

时间:2013-09-24 06:58:49

标签: c# exception

我希望能够捕获我的程序的每个异常并将其显示在MessageBox中,而不是仅仅说“已停止工作”的程序。

出于某种原因 - 每次软件出现故障时 - 程序说停止工作。我希望能够在MessageBox中显示它,就像在Visual Studio中一样。怎么可能?

C#WinForms。

5 个答案:

答案 0 :(得分:2)

订阅ThreadException和CurrentDomain.UnhandledException

static void Main(){
    Application.ThreadException += ApplicationThreadException;
    AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
}
static void ApplicationThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
    ShowGenericErrorMessage();
}
static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    ShowGenericErrorMessage();
}

答案 1 :(得分:0)

Global.asax 中的Application_Error方法是您最后一次抓住的机会:

protected void Application_Error(Object sender, EventArgs e)

答案 2 :(得分:0)

尝试类似:

public Form1()
        {
            InitializeComponent();
            AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException;
        }

        private void HandleUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show("Exception {0} was thrown", e.ToString());
        }

答案 3 :(得分:0)

试试这个:

try
{
\\Code block
}

catch(Exception ex)
{
\\the object ex has details about the exception use it display the error in msg box
}

此外,此链接仅解释了异常处理:http://www.dotnetperls.com/exception

答案 4 :(得分:0)

包装未处理的异常处理程序,如下所示:

static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
    Exception ex = (Exception)args.ExceptionObject;

    UtilGui.LogException(ex);
}

static void ApplicationThreadUnhandledExceptionHandler(object sender, System.Threading.ThreadExceptionEventArgs args)
{
    Exception ex = (Exception)args.Exception;

    UtilGui.LogException(ex);
}

并在Main方法中注册,如下所示:

// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ApplicationThreadUnhandledExceptionHandler);

// Set the unhandled exception mode to force all Windows Forms 
// errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomainUnhandledExceptionHandler);