如何在WCF服务中捕获异常?

时间:2019-02-09 23:32:53

标签: c# wcf exception-handling

我有一个计算器,该计算器使用来自2 TextBox的用户输入进行基本算术运算,并从使用listBox填充的NumericUpDown中得出平均值(众数,均值,中位数,范围) 。

计算在WCf服务中完成并返回。

对于基本算术,try catch足以处理一个空的textBox或不是double的任何东西。

尝试捕获无法达到平均值。如果数组为空,则会得到“ System.InvalidOperationException:   序列不包含任何元素”

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

表格

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

    }

看来我不能在服务代码中使用try catch,那么如何处理异常呢?

TIA!

0 个答案:

没有答案