3
Answers

Error handeling problems

Kenshin Hatake

Kenshin Hatake

14y
1.9k
1

Ok so I got the error events that I want set up but when I am runing it only the final result works when there are no error in the input data. But for instance when I put 0 in the gas used the results are printed is Infinity, and when I put in any number for the beging or ending miles it does the math regardless of what error are in the input data.
The Error I want to catch are;
gallons in gas and ending miles cannot be = to 0;
beging miles must be smaller than ending miles;
there can be no negative numbers;
and I want to print out what and where the error was entered. I got this set up pretty nice, but forsome reason it does not work the way I have it. I would appreciate any help on this.
 

 
private void menuItem2_Click(object sender, EventArgs e)
{

try
{
float gas = float.Parse(textBox1.Text);
float bMile = float.Parse(textBox2.Text);
float eMile = float.Parse(textBox3.Text);
//if gas or endmiles is 0 error
if (gas == 0 )
{
this.label6.Text = "Gallons is zero ";
}
if(eMile == 0)
{
this.label6.Text = "Ending Mileage is zero ";
}
//see if begining mileage is larger than ending mileage
if (bMile >= eMile)
{
this.label6.Text = "End mileage less than begin mileage ";
}
//if negative values are entered
if (gas < 0)
{
this.label6.Text = "Gallons is negative ";
}
if (bMile < 0)
{
this.label6.Text = "Begning Miles is negative ";
}
if (eMile < 0)
{
this.label6.Text = "Ending Miles is negative ";
}
this.label6.Text = String.Format("Result: {0}", (eMile - bMile) / gas);
}
catch (FormatException ex)
{
// string was not a number, handle the error or just use a formatted text box,
// NumericUpDown, etc.
}

}
Answers (3)