首先看一段C#代碼:運行後發現主線程通過try{}catch{}是不能撲捉子線程中的拋出來的異常。
代碼
class Program
{
static void Main(string[] args)
{
try
{
System.Threading.Thread thread = new System.Threading.Thread(new Program().run);
thread.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.Sleep(1000);
}
public void run()
{
throw new Exception();
}
}
為什麼呢?
首先需要瞭解異常的實現機制:異常的實現機制是嚴重依賴與線程的棧的。每個線程都有一個棧,線程啟動後會在棧上安裝一些異常處理幀,並形成一個鏈表的結構,在異常發生時通過該鏈表可以進行棧復原,如果你自己沒有安裝的話,可能會直接跳到鏈表尾部,那可能是CRT提供的一個預設處理幀,彈出一個對話方塊提示某某地址記憶體錯誤等,然後確認調試,取消關閉。
所以說,線程之間是不可能發生異常處理的交換關係的。
但是在實際的程式設計中,會牽涉到撲捉子線程的異常,那麼該怎樣解決這個問題呢?
代碼
class Program
{
private delegate void ExceptionHandler(Exception ex);
private static ExceptionHandler exception;
private static void ProcessException(Exception ex)
{
Console.WriteLine(ex.Message);
}
static void Main(string[] args)
{
exception = new ExceptionHandler(ProcessException);
System.Threading.Thread thread = new System.Threading.Thread(new Program().run);
thread.Start();
Thread.Sleep(1000);
}
public void run()
{
try
{
throw new Exception();
}
catch (Exception ex)
{
if (exception != null)
{
exception(ex);
}
}
}
}
上面使用委託的方式,間接的解決了:把子線程中的異常資訊交個主線程的一個方法去執行。(通過委託方式)
Best Reagrds,
Charles Chen