-1

I have a school project where I need to create a value returning method. When testing the program I found that if no value was entered into the text box it causes an error. I tried including a try catch statement but now the method shows not all code paths return a value. Can I use an If else and try catch statement together? If so how would it look, if not is there an easier solution?

Here is the code:

    private decimal TaxCharges()
    {
        decimal tax = 0.06m;
        decimal partsTax;
        try
        {
            partsTax = decimal.Parse(partsTextBox.Text) * tax;
            taxPartsTextBox.Text = partsTax.ToString("c");
            return partsTax;
        }
        catch
        { MessageBox.Show("Must enter 0 for parts");

        }
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Eysaak
  • 47
  • 1
  • 6

2 Answers2

0

First of all, you could initialize partsTax to have a default value:

decimal partsTax = 0;

Secondly, you can you use TryParse(), instead of Parse(), TryParse() will parse the value if it is parsable and otherwise your variable will have the default given value:

decimal partsTax = 0;
decimal.TryParse(partsTextBox.Text, out partsTax);
partsTax = partsTax * tax;
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
0

You can use this:

private decimal TaxCharges()
{
  decimal tax = 0.06m;
  if ( decimal.TryParse(partsTextBox.Text, out var partsTax) )
  {
    partsTax = partsTax * tax;
    taxPartsTextBox.Text = partsTax.ToString("c");
  }
  else
  {
    MessageBox.Show("Must enter 0 for parts");
  }
  return partsTax;
}

The TryParse method return false and set the value to 0 in case of error when converting.

You should take care that returning a 0 value in case of error is here an anti-pattern because you haven't computing anything that is equal to 0.

Hence you may prefer that:

private bool TaxCharges(out decimal partsTax)
{
  decimal tax = 0.06m;
  if ( decimal.TryParse(partsTextBox.Text, out partsTax) )
  {
    partsTax = partsTax * tax;
    taxPartsTextBox.Text = partsTax.ToString("c");
    return true;
  }
  else
  {
    MessageBox.Show("Must enter 0 for parts");
    return false;
  }
}

So now you can write:

decimal value;
if ( TaxCharges(out value) )
  DoSomething();
else 
  DoAnotherSomething();