locked
Exception handling RRS feed

  • Question

  • Hi all

    I'm creating exception handling in my program, but has a problem with getting it to work in a particular case.

    I convert some textboxes, and would like to catch any exceptions that might come. I thought I could just to wrap a try/catch block around the code where I perform the conversion, but if I do, I get an error further down in the code where I use the values from the text boxes.

    I could wrap it around more code, but is it not better to use try/catch on less code at a time?

    Example:

                 try
                {
                    string a = txtA.Text;
                    string b = txtB.Text;
                    string c = txtC.Text;
                    int x= Convert.ToInt32(txtX.Text);  
                }
                catch (FormatException ex)
                {
                    MessageBox.Show(ex);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex);
                }
    
                Class1 _class1 = new Class1 (a,b,c,x);
    
                try
                {
                    Class1.SomeMethod();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex);
                }
    

    It wont run because it does not recognize the variables in the class call. 

    I have tried to create the strings and the int before the conversion, but then it complains that the variables do not have any value assigned in the class call (the parameters). If I move the class call up in the try block - I get an error to the method call.

    Obviously I can wrap the entire code in the try block, but can it (or should it) be done in a different way?

    Wednesday, April 29, 2015 10:57 AM

Answers

  • Variables declared inside the try/catch/finally block have scope limited to that block so you can't use them outside of the block. If you declare the variable outside the block and then assign it inside the block then you can use them outside the try/catch/finally.

    string a = null; string b = null; string c = null; int x= 0; try { a = txtA.Text; b = txtB.Text; c = txtC.Text; x= Convert.ToInt32(txtX.Text); } catch (FormatException ex) { MessageBox.Show(ex);

    // return null; // this returns back to the calling code assuming that you are returning a reference type } catch (Exception ex) { MessageBox.Show(ex);

    // return null; // this returns back to the calling code assuming that you are returning a reference type } // you will still get an exception here because these variables might be null if an exception was thrown Class1 _class1 = new Class1 (a,b,c,x); try { Class1.SomeMethod(); } catch(Exception ex) { MessageBox.Show(ex); }


    You will still need to check to see if you have values assigned you can handle when you get to the creation of Class1 OR you can stop the method by calling return in the Exception block.


    Mark as answer or vote as helpful if you find it useful | Igor

    • Marked as answer by Zwax Thursday, April 30, 2015 5:39 AM
    Wednesday, April 29, 2015 11:09 AM

All replies

  • Variables declared inside the try/catch/finally block have scope limited to that block so you can't use them outside of the block. If you declare the variable outside the block and then assign it inside the block then you can use them outside the try/catch/finally.

    string a = null; string b = null; string c = null; int x= 0; try { a = txtA.Text; b = txtB.Text; c = txtC.Text; x= Convert.ToInt32(txtX.Text); } catch (FormatException ex) { MessageBox.Show(ex);

    // return null; // this returns back to the calling code assuming that you are returning a reference type } catch (Exception ex) { MessageBox.Show(ex);

    // return null; // this returns back to the calling code assuming that you are returning a reference type } // you will still get an exception here because these variables might be null if an exception was thrown Class1 _class1 = new Class1 (a,b,c,x); try { Class1.SomeMethod(); } catch(Exception ex) { MessageBox.Show(ex); }


    You will still need to check to see if you have values assigned you can handle when you get to the creation of Class1 OR you can stop the method by calling return in the Exception block.


    Mark as answer or vote as helpful if you find it useful | Igor

    • Marked as answer by Zwax Thursday, April 30, 2015 5:39 AM
    Wednesday, April 29, 2015 11:09 AM
  • As IWolbers said, though you could also move your use of the Class1 class inside the try block as well to avoid needing to jump out in the exception handler/check your variables later.

    string a = null; string b = null; string c = null; int x= 0; try { a = txtA.Text; b = txtB.Text; c = txtC.Text; x= Convert.ToInt32(txtX.Text);

    // You know the conversion has worked by this point (otherwise you would have jumped to the exception handlers) Class1 _class1 = new Class1 (a,b,c,x); Class1.SomeMethod(); } catch (FormatException ex) { MessageBox.Show(ex); } catch (Exception ex) { MessageBox.Show(ex); }


    Wednesday, April 29, 2015 11:13 AM
  • Hello,

    Two things stand out, where you created the variables, in the try-catch along with simply trying to convert. You should have the variables prior to the try and use TryParse to convert string to int.

    string a = txtA.Text;
    int x = 0;
    if (int.TryParse(a,out x))
    {
        // Conversion is good
    }
    else
    {
        // Conversion failed
    }
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

    Wednesday, April 29, 2015 4:27 PM
  • This should work as well.

    private void button1_Click(object sender, EventArgs e)
            {
                string a = txtA.Text;
                string b = txtB.Text;
                string c = txtC.Text;
                int x = 0;
    
                // Validate you text
                if(string.IsNullOrEmpty(txtX.Text))
                {
                    MessageBox.Show("A number must be provided for ....");
                }
    
                if(!ValidateInteger(txtX.Text))
                {
                    MessageBox.Show("You didn't provide a valid number for ...");
                }
    
                int.TryParse(txtX.Text, out x);
            }
    
            private bool ValidateInteger(string text)
            {
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("[0-9]");
                if(regex.IsMatch(text))
                {
                    return true;
                }
    
                return false;
            }

    • Proposed as answer by KyleS Wednesday, April 29, 2015 6:45 PM
    Wednesday, April 29, 2015 6:44 PM