简体   繁体   English

我在哪里将try-catch放入for循环中?

[英]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. 但是现在我想添加一个try-catch异常,以便如果用户输入的内容不是整数,它将抛出一个异常并说出类似的内容:输入错误,然后重试。 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. 该循环将循环10次并将输入存储在数组中。 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.. 当我尝试时,它要么成为一个异常,要么继续循环或中断循环,然后继续执行下一个代码块。

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 (eg something volatile such as filesystem interaction) that cannot be "predicted" so as to handle accordingly (eg log errors etc.) and then continue without crashing your program. 恕我直言,try / catch块仅应在未处理的异常(例如,诸如文件系统交互之类的易失性事件)存在无法“预测”以便相应处理(例如,日志错误等)的可能性时才真正使用继续而不会崩溃您的程序。

Always try and handle a "known" with the methods and functions available in the framework to do so. 始终尝试使用框架中可用的方法和功能来处理“已知”问题。

What you're trying to do doesn't require a try-catch . 您要尝试执行的操作不需要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. 您可以使用TryParse方法检查所需的输入是否为TryParse正确的整数,并提示用户输入其他输入。

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;

}

Use the int.TryParse method. 使用int.TryParse方法。

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块中使用它。 If the conversion fails, you can write the code for what you want to happen in the ELSE block. 如果转换失败,则可以在ELSE块中编写所需代码。 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. 如果列表中总共需要10个整数,则我放弃FOR循环,而推荐使用DO WHILE循环,该循环检查成功转换了多少个整数并将其添加到列表中。 It will keep requesting input until the list is filled with 10 integers. 它将一直请求输入,直到列表中填充了10个整数。

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);

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. 在这种情况下,可以改用int.TryParse() This block of code can replace your one int element... line: 此代码块可以替换您的一个int element...行:

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. i--是为了确保在下一次循环交互时i具有相同的值。 Doing that will make sure you still get 10 valid inputs before you finish the loop. 这样做将确保您在完成循环之前仍然获得10个有效输入。 (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.) (许多人会说这确实是一件很糟糕的事情,但是这样做的原因是可读性-如果您有一个较大的for循环并在中间某个位置递减值,那么下一个查看您代码的人将很难确切了解发生了什么。但这只是一个短循环,因此很明显。请注意这一点。

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). continue关键字将跳过循环的其余部分,然后continue进行下一个(这样就不会在数组中添加错误的值)。

If you want to keep your code with the try catch loop here it is: 如果您想将代码保留在try catch循环中,则为:

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 如果发生错误,goto语句将终止循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM