I have a calculator that does basic arithmetic using user input from 2 TextBox
and 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 catch
is 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!