3

I am getting this bug, I wrote code like this below

code:

decimal Amnt;
decimal.TryParse(txtAmnt.Text, out Amnt);
int tnure=1;
int.TryParse(txtTnre.Text, out tnure);
txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00");

when in textbox value 0 I am getting this error.If it is possible give answer to me.

gdoron
  • 147,333
  • 58
  • 291
  • 367
user1899761
  • 39
  • 1
  • 1
  • 5
  • 3
    What do you mean "solve"? Either validate value before division, or handle exception, if the validation isn't an option here. I hope, you don't looking for a way how to allow to divide by zero. – Dennis Mar 13 '13 at 05:28
  • check 'tnure!=0' value before the division operation take place. – asitis Mar 13 '13 at 05:40

4 Answers4

9

How about simply using an if to check before dividing by zero?

if(tnure != 0)
    txtDdctAmnt.Text = (Amnt / tnure).ToString("0.00");
else
    txtDdctAmnt.Text = "Invalid value";
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
3

check if tnure is not 0,you are getting Divide by Zero Exception,more help at http://msdn.microsoft.com/en-us/library/ms173160.aspx

decimal Amnt;
        decimal.TryParse(txtAmnt.Text, out Amnt);
        int tnure=1;
        int.TryParse(txtTnre.Text, out tnure);
if(tnure!=0)
{
        txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00");
}
else
{
/*handle condition*/
}
Cris
  • 12,799
  • 5
  • 35
  • 50
1

When tnre is 0, Amnt /tnure is a division by 0. You need to check whether tnre is 0 before dividing, and don't divide by tnre if it is equal to 0.

Max Nanasy
  • 5,871
  • 7
  • 33
  • 38
0

Put your code in try/Catch Statement like this

    try
    {
    decimal Amnt;
    decimal.TryParse(txtAmnt.Text, out Amnt);
    int tnure=1;
    int.TryParse(txtTnre.Text, out tnure);
    txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00");
    }
    catch(Exception ex)
    {
        // handle exception here
        Response.Write("Could not divide any number by 0");
    }
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83
  • 1
    Why do you wait to the exception? can't you check tnure? and never catch the global `Exception` exception. – gdoron Mar 13 '13 at 05:33