2

当我放入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");
        }

    }
4

1 回答 1

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

}

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

于 2012-11-26T14:38:05.007 回答