简体   繁体   中英

ReadKey method not working when application throws an exception

The ReadKey() method is not working when the method throws an exception? When the program runs the ReadKey method works only if the method dos not throw an exception, if the method throws an exception the console window just appears for a second or two.

Here is the method:

#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;
    }
}

}

Here is 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);
        }
    }
}

}

Once a method throws an exception, it stops working until you catch that exception. Since the exception is only caught at the Main method, the Console.ReadKey() method is never executed. If you want it to be executed, you may either catch the exception at DoWork or place the ReadKey method at or after catching the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM