[RESOLVED] Using Try And Catch In A Loop [How?]
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Thread: [RESOLVED] Using Try And Catch In A Loop [How?]

  1. #1
    Join Date
    Jun 2014
    Posts
    17

    [RESOLVED] Using Try And Catch In A Loop [How?]

    Back again, I've been programming all day lol and do not really know how to use try and catch in a while loop correctly.

    What I am trying to do is:

    1. Accept a float or integer in try { }

    2. Catch an error if a user entered something other than a float or int and re-loop.

    3. If the catch is not prompting any more errors break the loop.

    How would I do this in a small demonstration?

  2. #2
    Join Date
    Jan 2006
    Location
    Chicago, IL
    Posts
    14,985

    Re: Using Try And Catch In A Loop [How?]

    Just create a Boolean Flag, and change that in the loop.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,359

    Re: Using Try And Catch In A Loop [How?]

    Start coding up your problem by learning how to prompt the user for data in a while loop.

    Then add validation to the data. Instead of using a try/catch block, check out using TryParse methods, for example, Int32.TryParse() or Double.TryParse().

    Refer to msdn for specifics http://msdn.microsoft.com/en-us/libr...v=vs.110).aspx
    Last edited by Arjay; July 1st, 2014 at 07:15 PM.

  4. #4
    Join Date
    Jun 2014
    Posts
    17

    Re: Using Try And Catch In A Loop [How?]

    Quote Originally Posted by dglienna View Post
    Just create a Boolean Flag, and change that in the loop.
    I don't know what it is but I think I'm missing something in the if statement or a new variable. If it is the if statement how would I get exc to become false from the float "input" being a valid input. It just keeps re-looping. I only need it to re-loop if there is an exception and prompt it to enter a number again until they enter the correct value. Here is the Code:

    Code:
     static void Main(string[] args)
            {
                float input;
                bool exc = true;    //short for exception wich tells if there is an exception error
    
    
                /***< Exception Loop >***/
                while (exc == true)
                {
                    Console.WriteLine("Enter A Number:");
                    try
                    {
                        input = (float)Convert.ToDouble(Console.ReadLine());
                    }
                    catch
                    {
                        Console.WriteLine("\n");
                        Console.WriteLine("Error --> You Did Not Enter A Number Or Number With A Decimal! ");
                        Console.WriteLine("Re-Enter A Number");
                        Console.WriteLine("\n");
                        exc = true;
                    }
    
                    if (exc == false) // If there are no more errors stop the loop 
                    {
                        break;
                    }
                }
                Console.WriteLine("You Have Successfully Entered A Valid Input! :D");
                Console.WriteLine("\n");
                Console.WriteLine("Press Enter To End Program");
                Console.Read();
            }
    Last edited by Dylan3dx; July 2nd, 2014 at 12:53 PM.

  5. #5
    Join Date
    Apr 2014
    Location
    in northeast ohio
    Posts
    83

    Re: Using Try And Catch In A Loop [How?]

    follow the code blocks logic by the boolean's default state , they are tied together
    i.e.
    you can design the while block of code to work assuming success and continue but check for failure then reloop
    or
    you can design the while block of code to assume failure and loop until you explicitly meet some check
    before it will continue

    to say for your example
    Code:
    static void Main(string[] args)
            {
                float input;
                //
                // short for exception which tells if there is an exception error
                //  in truth this flag should not matter by default
                //  its more a reminder of the ideology of the code block were about to use 
                //  as i posted do we assume success and then check for failure 
                //  or assume failure and check for success, ... which is wiser ?
                // 
                bool exc = true;    
    
                /***< Exception Loop >***/
                while (exc == true)
                {
                    Console.WriteLine("Enter A Number:");
                    try
                    {
                        exc = false; // assume success
                        input = (float)Convert.ToDouble(Console.ReadLine());
                    }
                    catch  // check for failure
                    {
                        Console.WriteLine("\n");
                        Console.WriteLine("Error --> You Did Not Enter A Number Or Number With A Decimal! ");
                        Console.WriteLine("Re-Enter A Number");
                        Console.WriteLine("\n");
                        exc = true; // deal with failure by ensuring the while loop evaluates a repeat condition to true
                    }
                    //
                    // ---- uneeded code removed ----
                    //
                }
                Console.WriteLine("You Have Successfully Entered A Valid Input! :D");
                Console.WriteLine("\n");
                Console.WriteLine("Press Enter To End Program");
                Console.Read();
            }
    though both are basically the same
    i prefer TryParse as i think it is much easier to use
    its basically a wrapped up trycatch for parsing
    try parse can also be used culturally
    this is the general jist of it
    Code:
    string inputstr = "";
    float inputval = 0f;
    bool isparsedvaluegood = float.TryParse(inputstr, NumberStyles.Any, CultureInfo.InvariantCulture, out inputvar);
    if(isparsedvaluegood)
    { ... good value do something with it }
    else
    { ... invalid entry repeat send message or whatever ... }
    so this would be ur code with tryparse

    Code:
    static void Main(string[] args)
            {
                float inputval = 0f;
                bool exc = true;
                While(exc)
                {
                    Console.WriteLine("Enter A Number:");
                    string inputstr = Console.ReadLine();
                    //
                    if(true == float.TryParse(inputstr,out inputval) ) //true== is generally omited
                    {
                        exc = false;
                        Console.WriteLine("You Have Successfully Entered A Valid Input of "+ inputval.ToString());
                        Console.WriteLine("\n");
                        Console.WriteLine("Press Enter To End Program");
                        Console.Read();
                    }
                    else
                    {
                        exc = true;
                        Console.WriteLine("\n");
                        Console.WriteLine("Error --> You Did Not Enter A Number Or Number With A Decimal! ");
                        Console.WriteLine("Re-Enter A Number");
                        Console.WriteLine("\n");
                    }
                }
            }
    be-aware that inputval maybe filled with a junk value, if the tryparse returns false
    in that case it is no good as it was not successfully parsed (so you shouldn't use it as it is)
    it could be zero nan or max min value but you dont have to catch it
    this actually gives you a bit more flexability to write more complex stuff for instance
    you could manually save the previous value and reset it or to zero on parsing failure
    or say if the user typed "exit" instead of a number then...
    set the value to zero and another bool continue to false adding a message saying "im exiting"
    or on some bool having been set to false , you might simply not execute further code,
    that would have executed had the bool been true by default and never altered
    bypassing the rest of your executions you might have otherwise done
    to some point of the application closing or to some point of do you want to save ect...
    Last edited by willmotil; July 4th, 2014 at 06:28 PM.

  6. #6
    Join Date
    Jun 2014
    Posts
    17

    Re: Using Try And Catch In A Loop [How?]

    Quote Originally Posted by willmotil View Post
    follow the code blocks logic by the boolean's default state , they are tied together
    i.e.
    you can design the while block of code to work assuming success and continue but check for failure then reloop
    or
    you can design the while block of code to assume failure and loop until you explicitly meet some check
    before it will continue
    Thanks man this is exactly what I needed help on. Now I can finish my error check calculator.
    I really appreciate it. That shortened up my code quite a bit.

  7. #7
    Join Date
    Jun 2014
    Posts
    17

    Re: Using Try And Catch In A Loop [How?]

    Quote Originally Posted by willmotil View Post
    follow the code blocks logic by the boolean's default state , they are tied together
    i.e.
    you can design the while block of code to work assuming success and continue but check for failure then reloop
    or
    you can design the while block of code to assume failure and loop until you explicitly meet some check
    before it will continue
    Before I conclude the whole situation How would i use this for strings instead of finding integers. Is it try and catch for strings or something different?

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,359

    Re: Using Try And Catch In A Loop [How?]

    Console.Readline() already returns a string, i.e. there's nothing to do other than compare if you need to (check out the ignore case options).

  9. #9
    Join Date
    Jun 2014
    Posts
    17

    Re: Using Try And Catch In A Loop [How?]

    Quote Originally Posted by Arjay View Post
    Console.Readline() already returns a string, i.e. there's nothing to do other than compare if you need to (check out the ignore case options).
    Thanks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center