【问题标题】:ReadKey method not working when application throws an exception当应用程序抛出异常时,ReadKey 方法不起作用
【发布时间】:2013-09-27 09:54:27
【问题描述】:

ReadKey() 方法在方法抛出异常时不起作用?当程序运行时,ReadKey 方法只有在方法不抛出异常时才有效,如果方法抛出异常,控制台窗口只会出现一两秒钟。

方法如下:

#region Using directives
using System;
#endregion

namespace ParamsArray
{
class Util
{
    public static int Sum(params int[] paramList)
    {
        if (paramList == null)
        {
            throw new ArgumentException("Util.Sum: null parameter list");
        }
        if (paramList.Length == 0)
        {
            throw new ArgumentException("Util.Sum: empty parameter list");
        }

        int sumTotal = 0;
        foreach (int i in paramList)
        {
            sumTotal += i;
        }

        return sumTotal;
    }
}

}

这里是 Program.cs

#region Using directives

using System;
using System.Collections.Generic;
using System.Text;

#endregion

namespace ParamsArray
{
    class Program
    {
        static void DoWork()
        {
            Console.WriteLine(Util.Sum(null));
            Console.ReadKey();
        }

    static void Main()
    {
        try
        {
            DoWork();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex.Message);
        }
    }
}

}

【问题讨论】:

    标签: c# exception console-application console.readkey


    【解决方案1】:

    一旦方法抛出异常,它就会停止工作,直到您捕获该异常。由于异常仅在 Main 方法中被捕获,因此永远不会执行 Console.ReadKey() 方法。如果您希望它被执行,您可以在DoWork 处捕获异常,或者将ReadKey 方法放在捕获异常处或之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      相关资源
      最近更新 更多