0

I have a calculator that does basic arithmetic using user input from 2 TextBoxand works out averages(mode, mean, median, range) from a listBox thats populates using a NumericUpDown.

The calculations are done in WCf Service and returned.

For the basic arithmetic a try catchis enough to handle an empty textBox or anything thats not a double.

try catch isn't working for the averages. If the Array is empty, I get "System.InvalidOperationException: Sequence contains no elements"

Service.svc.cs

//Define the methods declared in ICalculator.cs by returning with the relevant maths for +, -, *, /, %
    public double Add2Numbers(double num1, double num2)
    {
        return num1 + num2;
    }


//Define the methods declared in ICalculator.cs by returning the mode from an array of decimals
    public decimal Mode(decimal[] ArrayofNumbers)
    {

         /*This is using LINQ to calculate mode.
         * taken from StackOverflow https://stackoverflow.com/questions/19407361/find-most-common-element-in-array/19407938
         * Groups identical values in the array
         * finds group with largest count*/
            decimal mode = ArrayofNumbers.GroupBy(v => v)
            .OrderByDescending(g => g.Count())
            .Select(g => g.Key)
            .First();

        return mode;
    }

Form

 //When this button is clicked num1 and num2 are added together
    private void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            //parse user input as double num1 and num2
            double num1 = double.Parse(txtNum1.Text);
            double num2 = double.Parse(txtNum2.Text);

            //Make a call to the service Add method, pass in num1 and num2
            txtBoxTotal.Text = ws.Add2Numbers(num1, num2).ToString();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex)
            MessageBox.Show("Enter a numeric value only please, thank you.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            txtBoxTotal.Text = String.Empty;
        }
    }

   //this button returns most common number in list
    private void BtnMode_Click(object sender, EventArgs e)
    {
        try
        {

            ws.Open();
            //Create new instance of listNumbers
            List<Decimal> listNumbers = new List<Decimal>();



            //for each decimal in listbox...
            foreach (Decimal listItems in listBoxNumbers.Items)
            {
                //Add to listNumbers
                listNumbers.Add(listItems);

            }

            //Convert list to array to find most common item
            decimal[] ArrayofNumbers = listNumbers.ToArray();

            //Print mode to label and console
            Console.WriteLine(ws.Mode(ArrayofNumbers).ToString());
            txtBoxResult.Text = ws.Mode(ArrayofNumbers).ToString();

            ws.Close();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex)
            MessageBox.Show("Enter some values to calculate averages, thank you.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

it seems I can't use try catch in the service code so how does one go about exception handling?

TIA!

  • so the `catch` clause in the `BtnMode_Click` doesn't catch anything? – kennyzx Feb 10 '19 at 02:27
  • @kennyzx: it catches the exception and prints it to console but the app crashes instead of showing the error box. **"An exception of type 'System.InvalidOperationException' occured in system.core.dll but was not handled in user code Sequence contains no elements"** –  Feb 10 '19 at 11:09
  • There should be error handling in the WCF service too, and in case of error throw FaultException from the service, while on the client side catch the FaultException. There are many examples to follow. Try to see if it helps. – kennyzx Feb 11 '19 at 01:50
  • I have tried similar code but I couldn't reproduce your problem. In my case, I could catch the exception and show it in the MessageBox, although I only use a console client. Or in your case , you could try to solve the exception in your service side, use a try catch or prevent the exception use FirstOrDefault [https://stackoverflow.com/questions/1324199/sequence-contains-no-elements](https://stackoverflow.com/questions/1324199/sequence-contains-no-elements) – Ackelry Xu Feb 11 '19 at 08:24

0 Answers0