【C#】42. 在线程中使用Try Catch

来源:互联网 发布:mac不能播放视频 编辑:程序博客网 时间:2024/05/29 09:03

本文主要说明:在线程函数中使用Try Catch能够正确捕获异常,而如果使用形如 try { var t = New Thread(XX); t.start(); } Catch{} 这种代码是无法正确处理异常的


using System;using System.Threading;namespace Chapter1.Recipe11{class Program{static void Main(string[] args){var t = new Thread(FaultyThread);t.Start();t.Join();try{t = new Thread(BadFaultyThread);t.Start();}catch (Exception ex){Console.WriteLine("无法在此处捕获错误!");}            Console.Read();}static void BadFaultyThread(){Console.WriteLine("Starting a faulty thread...");Thread.Sleep(2000);throw new Exception("Boom!");}static void FaultyThread(){try{Console.WriteLine("Starting a faulty thread...");Thread.Sleep(1000);throw new Exception("Boom!");}catch (Exception ex){Console.WriteLine("错误捕获: {0}", ex.Message);}}}}



0 0
原创粉丝点击