Simon
Simon

Reputation: 1

Where do i put the try-catch in my for-loop?

I'm now done with the basics of my code, and it works like it should. But now i want to add a try-catch exception so that if the user put is anything else than integers, it will throw an exception and say something like: Wrong input try again. Here is where i need it:

for (int i = 0; i < nummer.Length; i++)
                {

                    Console.Write("Nummer " + talnr + ": ");
                    talnr++;
                    string str = Console.ReadLine();
                    int element = Convert.ToInt32(str);
                    nummer[i] = element;

                }

The loop will loop 10 times and store the inputs in an array. When i try it either makes an exception but contiues the loop or breaks the loop and goes on to the next block of code..

Upvotes: 0

Views: 296

Answers (5)

Gabriel Luci
Gabriel Luci

Reputation: 41018

It's a good idea to not throw exceptions at all if you can help it. In this case, you can use int.TryParse() instead. This block of code can replace your one int element... line:

int element;
if (!int.TryParse(str, out element)) {
    Console.WriteLine("Bad!!");
    i--;
    continue;
}

The i-- is to make sure that i has the same value on the next interaction of the loop. Doing that will make sure you still get 10 valid inputs before you finish the loop. (Many will say this is a really bad thing to do, but the reason for that is readability - if you have a large for loop and decrement the value somewhere in the middle, it makes it difficult for the next guy looking at your code to understand exactly what's going on. But this is a short loop, so it's pretty obvious. Just be aware of this.)

The continue keyword skips the rest of that iteration of the loop and moves on to the next (so you don't add the bad value to your array).

Upvotes: -1

Eric Cartman
Eric Cartman

Reputation: 9

Use the int.TryParse method.

This code reads the trimmed input string from the user and tries to convert it to an integer. If the conversion is successful, it creates an integer variable called "result" which you can then use in the IF block. If the conversion fails, you can write the code for what you want to happen in the ELSE block. If you need a total of 10 integers in the list, I would drop the FOR loop in favor of a DO WHILE loop that checks for how many integers were successfully converted and added to the list. It will keep requesting input until the list is filled with 10 integers.

List<int> elements = new List<int>();

do
{
    Console.WriteLine("Please enter an integer.");

    if (int.TryParse(Console.ReadLine().Trim(), out int result))
    {
        Console.WriteLine($"You entered the integer {result}");
        elements.Add(result);
    }
    else
    {
        Console.WriteLine("You must enter an integer. Please try again.");
    }

} while (elements.Count < 10);

Upvotes: 0

Simkoo
Simkoo

Reputation: 74

If you want to keep your code with the try catch loop here it is:

for (int i = 0; i < nummer.Length; i++)
        {
            try { 

            Console.Write("Nummer " + talnr + ": ");
            talnr++;
            string str = Console.ReadLine();
            int element = Convert.ToInt32(str);
            nummer[i] = element;

            }
            catch
            {
                MessageBox.Show("Error, numbers only");
                goto breakloop;
            }

        }
        breakloop:;

The goto statement ends the loop if an error occured

Upvotes: -1

Mark Parker
Mark Parker

Reputation: 137

I would favour the use of...

bool parsed = Int.TryParse(str, out myInt);
If (parsed)
{
    // do something
}

IMHO, a try/catch block should only really be used when there is a possibility on an unhandled exception (e.g. something volatile such as filesystem interaction) that cannot be "predicted" so as to handle accordingly (e.g. log errors etc.) and then continue without crashing your program.

Always try and handle a "known" with the methods and functions available in the framework to do so.

Upvotes: 4

Hoppeduppeanut
Hoppeduppeanut

Reputation: 1169

What you're trying to do doesn't require a try-catch. You can use the TryParse method to check whether the desired input is a properly formed integer, and prompt the user to enter a different input.

for (int i = 0; i < nummer.Length; i++)
{
    bool isAnInteger = false;
    int element = 0;

    Console.Write("Nummer " + talnr + ": ");
    talnr++;
    string str = Console.ReadLine();

    // evaluates to true if str can be parsed as an int, false otherwise
    // and outputs the parsed int to element
    isAnInteger = int.TryParse(str, out element); 

    while (!isAnInteger)
    {
        Console.Write("Wrong input, try again. ");
        str = Console.ReadLine();
        isAnInteger = int.TryParse(str, out element);
    }


    nummer[i] = element;

}

Upvotes: 0

Related Questions