Where is the proper place to put a try/catch block in my program? I need to catch the exception that occurs when the user leaves a textbox blank. (input not in correct format) I want to do this:
CODE
try
{
//my code here;
if(my condition here)
{
//do something;
}
else
//do something else;
}
catch (Exception ex)
{ messageBox.Show("my error message here");
}
Is this done right? Can you have an if statement within a try catch block? It gives me errors when I try it.
Also, should I use methods to perform the calculations or is it proper as is? Could that be why I am getting the errors when I use the try/catch block, because I don't use methods, and the variables can't be accessed?
This is just a rough first draft...it does work without the try/catch, but I think it's kind of sloppy, and it doesn't account for all exceptions.
CODE
private void button1_Click(object sender, EventArgs e)
{
double miles, km, kg, pounds, miles2, knots, milesAns, kmAns, kgAns, poundsAns, miles2Ans, knotsAns;
//convert user input to numeric
miles = int.Parse(textBox1.Text);
km = int.Parse(textBox2.Text);
kg = int.Parse(textBox3.Text);
pounds = int.Parse(textBox4.Text);
miles2 = int.Parse(textBox5.Text);
knots = int.Parse(textBox6.Text);
//do not accept zeros
if (miles == 0 || km == 0 || kg == 0 || pounds == 0 || miles2 == 0 || knots == 0)
{
MessageBox.Show("please do not enter any zeros");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
}
else
{
//perform calculations
//1 Mile = 1.60934 Kilometers
kmAns = miles * 1.60934;
//1 Kilometer = 0.62137 Miles
milesAns = km * .62137;
//1 Pound = 0.45359 Kilograms;
kgAns = pounds * .45359;
//1 Kilogram = 2.20462 * Pounds;
poundsAns = kg * 2.20462;
//1 Miles Per Hour = 0.86898 Knot
knotsAns = miles2 * .86898;
//1.00000 Knot = 1.15078 Miles Per Hour
miles2Ans = knots * 1.15078;
//display results
textBox7.Text = kmAns.ToString();
textBox8.Text = milesAns.ToString();
textBox9.Text = kgAns.ToString();
textBox10.Text = poundsAns.ToString();
textBox11.Text = knotsAns.ToString();
textBox12.Text = miles2Ans.ToString();
}