如何在 C# 中重新引發 InnerException,而不會丟失堆疊軌跡?


在 c# 中,throw 關鍵字非常有用,它可以在程式執行期間手動引發異常,而且我們可以根據需要使用 try-catch 塊處理這些丟擲的異常。

透過在 catch 塊中使用 throw 關鍵字,我們可以重新引發在 catch 塊中處理的異常。重新引發異常很有用,當我們希望將異常傳遞給呼叫方以讓他們按照所需的方式處理時。

下面是如何使用 c# 的 try-catch 塊中的 throw 關鍵字重新向呼叫方引發異常。

示例

class Program{
   static void Main(string[] args){
      try{
         Method2();
      }
      catch (System.Exception ex){
         System.Console.WriteLine($"{ex.StackTrace.ToString()} {ex.Message}");
      }
      Console.ReadLine();
   }
   static void Method2(){
      try{
         Method1();
      }
      catch (System.Exception){
         throw;
      }
   }
   static void Method1(){
      try{
         throw new NullReferenceException("Null Exception error");
      }
      catch (System.Exception){
         throw;
      }
   }
}

這是我們如何根據需要使用 catch 塊中的 throw 關鍵字重新向呼叫方引發異常。

輸出

at DemoApplication.Program.Method1() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 49
at DemoApplication.Program.Method2() in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 37
at DemoApplication.Program.Main(String[] args) in C:\Users\Koushik\Desktop\Questions\ConsoleApp\Program.cs:line 24 Null Exception error

更新於: 05-11-2020

1K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始吧
廣告
© . All rights reserved.