Home > Blockchain >  How can I try/catch an exception for a negative number in c#?
How can I try/catch an exception for a negative number in c#?

Time:04-22

My program is simply a square root I take an integer from the user in a TextBox and give the result using the function Math.Sqrt in the other TextBox. What I am trying to do now is to show a MessageBox using try/catch exceptions that tells the user he can't use a negative number I used if statement but did not show the MessageBox just getting NaN value, please if anyone could help

        int num1;
        try
        {
            num1 = System.Convert.ToInt32((textBox1.Text));
            textBox2.Text = System.Convert.ToString(Math.Sqrt(num1));
        }

        catch (FormatException)
        {
            MessageBox.Show("Data type is wrong");
        }

        catch (Exception)
        {
            num1 = 0;
            if (num1 < 0)

            MessageBox.Show("Number must be positive");
            
        }

CodePudding user response:

Usually, exceptions are used to manage rare events. Manage exceptions it's costly. In your case, maybe normal a typo error or even a negative number. It's better manage as a normal thing.

int num1;
if (int.TryParse(textBox1.Text, out num1) && num1 >= 0)
{
    textBox2.Text = Convert.ToString(Math.Sqrt(num1));
}
else
{
    MessageBox.Show("You must enter a positive number");
}

CodePudding user response:

Check the documentation for Math.Sqrt(). This function doesn't throw an exception when number is negative. This is first reason why the code for catch(Exception){} is not being executed.

Secondly you are setting

num1 = 0;

and then next checking

if(num<0){} // This will always be false

Anyways I recommend to check the num1 value before you calculate the root

int num1;
try
{
    num1 = System.Convert.ToInt32((textBox1.Text));
    if (num1 < 0)
        MessageBox.Show("Number must be positive");
    else
        textBox2.Text = System.Convert.ToString(Math.Sqrt(num1));
}
catch (FormatException)
{
    MessageBox.Show("Data type is wrong");
}
catch (Exception)
{
}
  • Related