我有重新拋出異常的代碼。重新拋出任務異常(TPL)失去堆棧跟蹤
當我稍後從task.Exception中讀取異常時,它的堆棧跟蹤指向我重新拋出異常的位置(第n行而不是第m行,如我所料)。
這是爲什麼? TPL中的錯誤或更可能是我忽視的東西。
由於我的解決方法是我可以將異常作爲內部異常包裝在新的異常中。
internal class Program
{
private static void Main(string[] args)
{
Task.Factory.StartNew(TaskMethod).ContinueWith(t => Console.WriteLine(t.Exception.InnerException));
Console.Read();
}
private static void TaskMethod()
{
try
{
line m: throw new Exception("Todo");
}
catch (Exception)
{
line n: throw;
}
}
}
替換行號問題的'throw'是相當有名的。有一篇[博客文章](http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx)討論了一種可能解決方法,但我沒有使用它自己。 –