【问题标题】:C# final block is not executing when exception thrown from catch当从 catch 抛出异常时,C# final 块没有执行
【发布时间】:2012-11-14 00:42:16
【问题描述】:

当我将SecondMain() 放入try blcok 时,secondMain() 中的最后一个块正在执行。但是当我把它放在外面时它没有执行。为什么不执行?

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");
        }

    }

【问题讨论】:

    标签: try-catch finally


    【解决方案1】:

    我试过你的代码,不管是从 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");
        }
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多