2012-11-26 75 views
2

當我把SecondMain()裏面的嘗試blcok secondMain()內的最後一塊正在執行。但是當我把它放在外面的時候它並沒有執行。爲什麼它不執行?C#最後的塊沒有執行時,拋出異常拋出

static void Main(string[] args) 
    { 

     try 
     { 
      SecondMain(args); //try putting 
      Console.WriteLine("try 1"); 
      throw new Exception("Just fail me");    
     }    
     finally 
     { 
      Console.WriteLine("finally"); 
     } 

    } 


    static void SecondMain(string[] args) 
    { 

     try 
     { 
      throw new StackOverflowException(); 
     } 
     catch (Exception) 
     { 
      Console.WriteLine("catch"); 
      throw; 
     } 
     finally 
     { 
      Console.WriteLine("finally"); 
     } 

    } 

回答

0

我試過你的代碼,不管是從外部還是從try塊內部調用SecondMain()方法都沒有關係。

該程序總是崩潰,因爲你不處理例外和從.Net環境中的MainExceptionHandler必須照顧到這一點。他得到一個未處理的異常並退出程序。

試試這個,現在我認爲你的代碼行爲像預期的那樣。

static void Main(string[] args) 
{ 

    try 
    { 
     SecondMain(args); //try putting 
     Console.WriteLine("try 1"); 
     throw new Exception("Just fail me");    
    } 
    catch(Exception) 
    { 
     Console.WriteLine("Caught"); 
    }  
    finally 
    { 
     Console.WriteLine("finally"); 
    } 

} 


static void SecondMain(string[] args) 
{ 

    try 
    { 
     throw new StackOverflowException(); 
    } 
    catch (Exception) 
    { 
     Console.WriteLine("catch"); 
     //throw; 
    } 
    finally 
    { 
     Console.WriteLine("finally"); 
    } 

} 

我希望這是您正在尋找的答案。