我自己的异常处理程序仍然抛出异常并使应用程序崩溃

时间:2017-01-26 14:55:27

标签: c# winforms exception-handling handler

Winforms app。 这是主要的:

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

        // Add handler for UI thread exceptions
        Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);

        // Force all WinForms errors to go through handler
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

        // This handler is for catching non-UI thread exceptions
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        Application.Run(new Form1());
    }

    private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
    {
            Exception ex = (Exception)e.ExceptionObject;
            MessageBox.Show("Unhadled domain exception:\n\n" + ex.Message);

            Application.Exit();


        // It should terminate our main thread so Application.Exit() is unnecessary here
    }

    private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
    {
         MessageBox.Show("Unhandled exception catched.\n Application is going to close now.");


        // Here we can decide if we want to end our application or do something else
        Application.Exit();
    }
}

这是我故意生成异常的地方

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            int zero = 0;
            //int number = 1 / zero;

            throw new System.IO.FileNotFoundException();
        }
    }

堆栈跟踪:

    System.IO.FileNotFoundException was unhandled
  HResult=-2147024894
  Message=Unable to find the specified file.
  Source=NewPostSharpSolution
  StackTrace:
       at NewPostSharpSolution.Form1..ctor() in C:\Users\Joao\Documents\Visual Studio 2015\Projects\NewPostSharpSolution\NewPostSharpSolution\Form1.cs:line 21
       at NewPostSharpSolution.Program.Main() in C:\Users\Joao\Documents\Visual Studio 2015\Projects\NewPostSharpSolution\NewPostSharpSolution\Program.cs:line 30
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

处理程序显示异常的消息框但仍然破坏了应用程序...

我有什么遗失的吗?我认为实现这个处理程序会让我决定如何处理异常??

2 个答案:

答案 0 :(得分:4)

来自MSDN AppDomain.UnhandledException Event

  

此事件提供未捕获异常的通知。它允许应用程序在系统默认处理程序向用户报告异常并终止应用程序之前记录有关异常的信息。

这意味着 - 您无法处理异常。您可以记录有关异常的信息,显示一些消息等。但是您无法阻止应用程序终止。

答案 1 :(得分:0)

尽管在捕获未处理的异常时(在生成错误报告之后)终止应用程序是最佳做法,但处理此事件肯定会关闭应用程序。

在您的情况下,应用程序终止,因为您在Form1的构造函数中抛出异常,该构造函数在Main方法中实例化。 因此,您最终会在Main方法中出现未处理的异常。

例如,在您的表单的Load事件中抛出异常,您的应用将不会被关闭(除非您将Application.Exit行留在那里......)

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.ThreadException += Application_ThreadException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.ToString());
    }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        // throw new Exception("Crash");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        throw new Exception("No crash");
    }
}