I was wondering if i could get a hand please. Can someone explain to me why my string sqrt
is unassigned in the finally
block? Why do I have to declare it? Why can't it be declared in the try or catch statement? It would make coding less tedious and more organized.
private void btnDisplay_Click(object sender, EventArgs e)
{
int number;
string sqrt;
try
{
number = Convert.ToInt32(tbInput.Text);
//Why cant i just have it as "number=COnvert.ToDouble(tbInput.Text)?//
Convert.ToDouble(number);
if (number < 0)
{
throw new NegativeNumberException();
}
sqrt = Math.Sqrt(number).ToString();
}
catch (FormatException error)
{
lbOutput.Items.Add(error.Message);
lbOutput.Items.Add("The input should be a number.");
sqrt = "not able to be calculated";
}
catch (NegativeNumberException neg)
{
lbOutput.Items.Add(neg.Message);
sqrt = "not able to be calculated";
}
finally
{
//Here is where i am having the issue "Unassigned local variable"//
lbOutput.Items.Add("Square Root " + sqrt);
}
}
class NegativeNumberException : Exception
{
public NegativeNumberException()
: base("Number can’t be negative")
{
}
}
}
}
What I am attempting to achieve in the finally block is for "Square Root" and "sqrt" to be displayed in the list box no matter what the value of sqrt is. If I output sqrt to the list box in any of the other blocks, it works (because it has been declared). Does anyone know how can I can do this? I bet it's probably something simple too. I don't mean to rant or anything its just I have been up for the last 12 hours so I am begin to feel defeated. I appreciate everyone's help, I truly do.