2

I can't figure out how to get the try catch to work. Need to have an error message box pop up when a non number is entered in the text boxes.

private void btnAdd_Click(object sender, EventArgs e)

    {
        int x = int.Parse(txtIn1.Text);
        int y = int.Parse(txtIn2.Text);

        txtIn1.Text = x.ToString();
        txtIn2.Text = y.ToString();

        lstOut.Items.Add((x + y).ToString("N0"));

        try
        {
            int.Parse(txtIn1.Text);
            int.Parse(txtIn2.Text);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272

4 Answers4

4

With minimal modifications: move all the code into the try so it catches when any Exception is hit. You're encountering your exception outside of the try block. You are only going to ever see your catch triggered if something within the corresponding try block is throw an exception.

private void btnAdd_Click(object sender, EventArgs e) {
    try {
      int x = int.Parse(txtIn1.Text);
      int y = int.Parse(txtIn2.Text);

      txtIn1.Text = x.ToString();
      txtIn2.Text = y.ToString();

      lstOut.Items.Add((x + y).ToString("N0"));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
    }
}

Edit: As suggested by commenters, I think this answer is incomplete without stating that a Try/Catch block is overkill in this instance.

A better approach would be to use the built-in TryParse method (which can return a boolean regarding the success of the parse attempt, and an output value). Here is one way you could accomplish this:

private void btnAdd_Click(object sender, EventArgs e) {
  var xSuccess = int.TryParse(txtIn1.Text, out int x);
  var ySuccess = int.TryParse(txtIn2.Text, out int y);

  if(!xSuccess)
    MessageBox.Show($"{x} could not be parsed to int!");
  if(!ySuccess)
    MessageBox.Show($"{y} could not be parsed to int!");

  if(xSuccess && ySuccess)
    lstOut.Items.Add((x + y).ToString("N0"));
}
Miek
  • 1,190
  • 7
  • 18
  • 1
    Really shouldn't use a try/catch when a simple `int.TryParse()` would suffice and not have tons of overhead like try/catch – maccettura Oct 13 '17 at 18:34
  • @maccettura I agree with your comment in general. In this case, I was aiming to show him the smallest adjustment to his code to achieve his goal to demonstrate how that block actually functions. Perhaps a better solution would have been to explain how the block would perform and still use TryParse in place of the Try/Catch. Thanks for your feedback – Miek Oct 13 '17 at 18:48
  • 1
    you can always edit your question to include the better way of doing things. Remember SO isn't _just_ about answering the questions. It's also a learning opportunity. So if you see something that the OP could do differently, make sure you let them know! – maccettura Oct 13 '17 at 18:49
3

You shouldn't use try-catch as a control block as explained in this SO post. Use if for that. Try catch is really meant to be used when you can't do otherwise or when something that you didn't expect happened.

You can use this SO post as an example and your code could look like this

private void btnAdd_Click(object sender, EventArgs e)
{
    int x;
    int y;

    if(!int.TryParse(txtIn1.Text, out x) || !int.TryParse(txtIn2.Text, out y))
        MessageBox.Show("Parse failed !");          
}

You can use

Console.WriteLine(x);
Console.WriteLine(y);

to verify that the vars were properly given a value

For more information about the int.TryParse() method vs int.Parse() see this post

Mathieu VIALES
  • 4,526
  • 3
  • 31
  • 48
2

As other have mentioned, it's the first int.Parse() functions that are tripping things up - the ones outside the Try/Catch block.

I wanted to expand on the TryParse() function - and why should probably be using that.

Exceptions are expensive - they're a rather large overhead in terms of Time/CPU/etc. They're also not user-friendly. You want to say "Please enter a valid number" to the user, not "An exception occurred: ..."

Instead, you can use TryParse, which returns whether the parsing worked; the output of the parse is an "out" parameter in the inputs list:

int myValue;
bool parseWorked = int.TryParse("3", out myValue);

This doesn't have the Exception overhead - it runs quickly, regardless of whether the input's valid.

Kevin
  • 2,133
  • 1
  • 9
  • 21
1

Why not use a different approach?

Use the TextBox.KeyPress event:

private void txtIn1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) /* || add more conditions*/)
        e.Handled = true; // Prevent key to be added to the TextBox' text.
}

Now you don't have to check if there are non-numbers in your string.

Your statement int.Parse(txtIn1.Text); will surely work.