MSDN中关于Winform异常处理

43 篇文章 1 订阅

Thread newThread = null;

 

// Starts the application.

[SecurityPermission(SecurityAction.Demand,Flags = SecurityPermissionFlag.ControlAppDomain)]

public static void Main(string[]args)

{

    // Add the event handler for handling UIthread exceptions to the event.

   Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

 

    // Set the unhandled exception mode to forceall Windows Forms errors to go through

    // our handler.

    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

 

    // Add the event handler for handling non-UIthread exceptions to the event.

   AppDomain.CurrentDomain.UnhandledException +=

       new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

 

    // Runs the application.

   Application.Run(new ErrorHandlerForm());

}

 

// Programs the button to throw an exceptionwhen clicked.

private void button1_Click(objectsender, System.EventArgs e)

{

    throw new ArgumentException("The parameter was invalid");

}

 

// Start a new thread, separate from WindowsForms, that will throw an exception.

private void button2_Click(objectsender, System.EventArgs e)

{

   ThreadStart newThreadStart = new ThreadStart(newThread_Execute);

   newThread = new Thread(newThreadStart);

   newThread.Start();

}

 

// The thread we start up to demonstratenon-UI exception handling.

void newThread_Execute()

{

    throw new Exception("The method or operation is not implemented.");

}

 

// Handle the UI exceptions by showing adialog box, and asking the user whether

// or not they wish to abort execution.

private static void Form1_UIThreadException(object sender, ThreadExceptionEventArgs t)

{

   DialogResult result = DialogResult.Cancel;

    try

    {

       result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception);

    }

    catch

    {

       try

       {

           MessageBox.Show("FatalWindows Forms Error",

                "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Stop);

       }

       finally

       {

           Application.Exit();

       }

    }

 

    // Exits the program when the user clicksAbort.

    if (result == DialogResult.Abort)

       Application.Exit();

}

 

// Handle the UI exceptions by showing adialog box, and asking the user whether

// or not they wish to abort execution.

// NOTE: This exception cannot be kept fromterminating the application - it can only

// log the event, and inform the user aboutit.

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

{

    try

    {

       Exception ex = (Exception)e.ExceptionObject;

       string errorMsg = "An application error occurred. Please contact theadminstrator " +

           "with thefollowing information:\n\n";

 

       // Since we can'tprevent the app from terminating, log this to the event log.

       if (!EventLog.SourceExists("ThreadException"))

       {

           EventLog.CreateEventSource("ThreadException", "Application");

       }

 

       // Create an EventLoginstance and assign its source.

       EventLog myLog = new EventLog();

       myLog.Source = "ThreadException";

       myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);

    }

    catch (Exception exc)

    {

       try

       {

           MessageBox.Show("FatalNon-UI Error",

                "Fatal Non-UI Error. Could not write the error tothe event log. Reason: "

                + exc.Message,MessageBoxButtons.OK, MessageBoxIcon.Stop);

       }

       finally

       {

           Application.Exit();

       }

    }

}

 

// Creates the error message and displays it.

private static DialogResult ShowThreadExceptionDialog(string title, Exception e)

{

    string errorMsg = "An application error occurred. Please contact the adminstrator" +

       "with thefollowing information:\n\n";

   errorMsg = errorMsg + e.Message + "\n\nStack Trace:\n" + e.StackTrace;

    return MessageBox.Show(errorMsg, title,MessageBoxButtons.AbortRetryIgnore,

       MessageBoxIcon.Stop);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值