2017-02-19 107 views
1
static void Main(string[] args) 
     { 
      try 
      { 
       var intValue = "test"; 
       var test = Convert.ToInt32(intValue); 
      } 
      catch (FormatException) 
      { 
       Console.WriteLine("format exception"); 
       throw; 
      } 
      catch (Exception) 
      { 

      } 
      finally 
      { 
       Console.WriteLine("finally"); 
      } 
     } 

據我所知,在從字符串轉換爲int的過程中,引發了一個FormatException。現在在catch塊中,我們重新拋出原始異常。爲什麼這不會被捕獲到泛型異常catch塊?如果我把try/catch放在throw上,那麼應用程序不會崩潰。爲什麼這個C#代碼會導致進程崩潰?

回答

5

爲什麼這不會被捕獲到泛型異常catch塊?

由於一般異常塊捕獲被拋出僅在try塊,不趕上從catch塊拋出的異常的異常。

所以,如果你打算從catch塊中拋出一個異常,並且你想要處理它,你將需要在另一個try/catch中包裝調用代碼。