2012-11-26 121 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"); 
    } 

} 

我希望这是您正在寻找的答案。