【问题标题】:Catch error before starting the loop [closed]在开始循环之前捕获错误[关闭]
【发布时间】:2015-12-11 08:50:16
【问题描述】:

编辑:提供更多代码。

我有一个看起来像这样的 for 循环:

public void SendCommand(string userInput)
{
    string[] _command = userInput.Split('#', '>');
    string[] _keypress = _command.Where((value, index) => index % 2 == 0).ToArray(); //Even array = Keypress
    string[] _count = _command.Where((value, index) => index % 2 != 0).ToArray(); // Odd array = keypress count
    int keypressLength = _keypress.GetLength(0);

    for (int j = 0; j < keypressLength; j++) //loop through all indices
    {
        for (int i = 0; i < int.Parse(_count[j]); i++) //repeat convert command for #X times
        {
            ConvertCommand(_keypress[j]);
            Thread.Sleep(100); // wait time after each keypress
        }
    }
}

在上面的代码周围加上'try-catch',如果用户输入无效,将在循环中途抛出异常。但是,我想在循环开始之前捕获错误,我该如何实现呢?

【问题讨论】:

  • 验证用户输入并向他显示一条消息..如果有效输入继续您的循环!
  • 在不知道ConvertCommand 的性质的情况下,我们不可能知道a)如何预先检查一切是否正常,b)是否甚至可以预先检查(即是否有任何与外部系统的交互,再多的预检查都不会告诉您该命令是否会在到您实际尝试它时起作用)
  • 哪一部分是无效输入 - _count[j]_keypress[j]?而且我会亲自为外循环的每次迭代执行一次解析,而不是为内循环的每次迭代执行一次...
  • 验证前面输入的问题在哪里,如果有效则继续?如果您的循环中的任何命令引发异常,应用程序在执行之前应该如何停止?

标签: c# for-loop try-catch


【解决方案1】:

您可以使用int.TryParse。它尝试解析字符串并返回truefalse

for (int j = 0; j < keypressLength; j++) //loop through all indices
{
    int limit;        
    if (!int.TryParse(_count[j], out limit))
    {
        // Show an error like "_count[j] cannot be parsed"
        continue;
    }

    for (int i = 0; i < limit; i++)
    {
        ConvertCommand(_keypress[j]);
        Thread.Sleep(100); // wait time after each keypress
    }
 }

如果用户不断输入不正确的数据,您可能还想在 ConvertCommand 中实施某种验证。

更新:

例如,_count[0] 可以被解析,但 _count[1] 不能,当它发现错误时,_count[0] 已经被处理了。如果有任何错误,我不希望它们中的任何一个被处理。

您可以使用相同的int.TryParse 并利用LINQ 检查_count 中的所有字符串是否可以解析为整数:

int stub;
if (_count.Any(x => !int.TryParse(x, out stub)))
{
    // There is a non-integer string somewhere!
}

for (int j = 0; j < keypressLength; j++) //loop through all indices
{
    for (int i = 0; i < int.Parse(_count[j]); i++)
    {
        ConvertCommand(_keypress[j]);
        Thread.Sleep(100); // wait time after each keypress
    }
 }

【讨论】:

  • 例如,_count[0] 可以解析,但_count[1] 无法解析,当它发现错误时,_count[0] 已经被处理。如果有任何错误,我不希望它们中的任何一个被处理。
  • @Liren 检查更新的答案。
  • 谢谢!我一直在研究try-catch,完全走错了方向。
猜你喜欢
  • 2022-11-04
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多