dotnet C# 如何修改異常的堆棧
實現方法非常簡單,通過 ExceptionDispatchInfo.SetRemoteStackTrace 方法即可修改異常堆棧,如以下示例
var exception = new ArgumentException();
ExceptionDispatchInfo.SetRemoteStackTrace(exception, $@"栽贓的堆棧.{nameof(Foo)}.{nameof(Foo.F1)}
Main");
Console.WriteLine(exception);
此時控制臺輸出內容大概如下
System.ArgumentException: Value does not fall within the expected range.
栽贓的堆棧.Foo.F1
Main
--- End of stack trace from previous location ---
如果想要對外拋出此加工后的異常,直接使用 throw exception; 扔掉即可,異常打印信息大概如下
System.ArgumentException: Value does not fall within the expected range.
栽贓的堆棧.Foo.F1
Main
--- End of stack trace from previous location ---
at Program.<Main>$(String[] args)
或者使用 ExceptionDispatchInfo.Throw 扔也可以,代碼示例如下
ExceptionDispatchInfo.Throw(exception);
異常打印信息大概如下
System.ArgumentException: Value does not fall within the expected range.
栽贓的堆棧.Foo.F1
Main
--- End of stack trace from previous location ---
at Program.<Main>$(String[] args)
可見此時 throw exception; 和 ExceptionDispatchInfo.Throw(exception); 行為接近。正常來說會使用到 ExceptionDispatchInfo.Throw 方法的,都是針對于已經被拋出過的異常,進行重新捕獲,延遲拋出的情況,詳細請看 使用 ExceptionDispatchInfo 捕捉并重新拋出異常 - walterlv
本文代碼放在 github 和 gitee 上,可以使用如下命令行拉取代碼。我整個代碼倉庫比較龐大,使用以下命令行可以進行部分拉取,拉取速度比較快
先創建一個空文件夾,接著使用命令行 cd 命令進入此空文件夾,在命令行里面輸入以下代碼,即可獲取到本文的代碼
git init
git remote add origin https://gitee.com/lindexi/lindexi_gd.git
git pull origin ecffc754e5ae60028556594d962d39a42d8b6bc0
以上使用的是國內的 gitee 的源,如果 gitee 不能訪問,請替換為 github 的源。請在命令行繼續輸入以下代碼,將 gitee 源換成 github 源進行拉取代碼。如果依然拉取不到代碼,可以發郵件向我要代碼
git remote remove origin
git remote add origin https://github.com/lindexi/lindexi_gd.git
git pull origin ecffc754e5ae60028556594d962d39a42d8b6bc0
獲取代碼之后,進入 Workbench/FehallladaichaWhearjechelra 文件夾,即可獲取到源代碼
更多技術博客,請參閱 博客導航
博客園博客只做備份,博客發布就不再更新,如果想看最新博客,請訪問 https://blog.lindexi.com/
如圖片看不見,請在瀏覽器開啟不安全http內容兼容

本作品采用知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可。歡迎轉載、使用、重新發布,但務必保留文章署名[林德熙](http://www.rzrgm.cn/lindexi)(包含鏈接:http://www.rzrgm.cn/lindexi ),不得用于商業目的,基于本文修改后的作品務必以相同的許可發布。如有任何疑問,請與我[聯系](mailto:lindexi_gd@163.com)。

浙公網安備 33010602011771號