全局异常处理程序实现C#WinForms

时间:2020-09-01 21:10:14

标签: c# winforms design-patterns

我正在尝试实现全局的“ try catch block”,并在处理任何问题后保持我的应用运行:

public class GlobalExceptionHandler
{
    public GlobalExceptionHandler()
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    }
    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        try
        {
            throw (e.ExceptionObject as Exception);
        }
        catch (Exception ex)
        {
        }
    }
}

问题:

  1. 我希望使用try catch块以熟悉的方式处理所有异常。我把它们扔掉抓错了吗?
  2. 上面的代码仍将应用程序丢弃,并在最初引发异常的地方弹出异常弹出窗口,就像未处理一样。
  3. 猜猜我的方法从一开始就是彻底失败。我想避免在整个应用程序中使用大量try catch块,而是决定对所有异常处理进行本地化。这个想法有多好?我是否应该找到实现全局处理程序的更好方法,还是坚持使用数十个try catch块?

1 个答案:

答案 0 :(得分:0)

Windows窗体具有单独的event,用于处理GUI线程上的异常(即,在诸如按钮单击,文本框文本更改等GUI事件上发生的异常):

Application.ThreadException += new ThreadExceptionEventHandler(Handler);
    
public void Handler(object sender, ThreadExceptionEventArgs t)
{
        //exceptions handling code here...
        

        // you can throw exception at the end of method if you want this exception to go unhandled, not writing throw will swallow exception
        /// throw t.Exception
}