测试环境:
win10 + VS2013
一,点击主窗口的异常,可以catch到。
二,弹出的新窗口的按钮异常,可以catch到。
三,System.Timers.Timer的异常catch不到。
四,新线程catch不到。
一,建立一个WinForm项目。
static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } catch(System.Exception ex) { MessageBox.Show(ex.ToString()); } }
在Form1上增加4个按钮,响应函数如下:
private void button1_Click(object sender, EventArgs e) { Throw(); } private void button2_Click(object sender, EventArgs e) { Form2 form = new Form2(); form.ShowDialog(); } public void ThrowOnTimer(object source, System.Timers.ElapsedEventArgs e) { throw (new System.Exception("自定义异常")); } private void button3_Click(object sender, EventArgs e) { System.Timers.Timer t = new System.Timers.Timer(500);//实例化Timer类,设置间隔时间为10000毫秒; t.Elapsed += new System.Timers.ElapsedEventHandler(ThrowOnTimer);//到达时间的时候执行事件; t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件; } void Throw() { throw (new System.Exception("自定义异常")); } private void button4_Click(object sender, EventArgs e) { System.Threading.Thread thread = new System.Threading.Thread(Throw); thread.Start(); }
增加一个WinForm
private void button1_Click(object sender, EventArgs e) { Form2 form = null; form.ShowDialog(); } //处理UI线程异常 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(doEx.ThreadExceptionEventHandler); //处理非UI线程异常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(doEx.UnhandledExceptionEventHandler);
可以截获异常,但无法取消系统的处理。