Domanda

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

}

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top