try / catch阻止功能限制

时间:2018-01-31 16:25:42

标签: c# try-catch

我希望程序的用户能够重复操作,直到他们通过输入某个字符串来指示程序停止运行。我试图通过使用:

输入单词“stop”来允许用户停止程序
If (sequenceSelector.ToUpper().Contains("stop"))    
{
    //code to do stuff here
}

目前,可以访问变量sequenceSelector的唯一位置是封装在此try块中。

try
{                    
    int sequenceSelector = Convert.ToInt32(Console.ReadLine());

    if (sequenceSelector <=0)
    {
        throw new IndexOutOfRangeException();
    }
    String outputString = "[" + sequenceSelector.ToString() + "]: ";
    for (int i = 0; i < sequenceSelector; i++)
    {
        outputString = outputString + fibonacciSequence.GetValue(i).ToString() + ", ";
    }

    Console.WriteLine(outputString);

    return sequenceSelector;
}

这会导致问题,因为其中一个catch块是:

catch (FormatException)
{
    Console.WriteLine("Invalid input detected! Please enter a number that is not <=0 and not > 20");
    return null;
}

这可以防止用户输入任何非数字字符,因为sequenceSelector必须是int才能使程序正常运行。

我希望能够让用户输入单词“stop”作为程序的一部分。我怎样才能绕过异常处理才能做到这一点?

2 个答案:

答案 0 :(得分:7)

使sequenceSelector成为int字符串并使用int.TryParse检查它是否可转换为string sequenceSelector = Console.ReadLine(); int intValue; if(int.TryParse(sequenceSelector, out intValue)) { if (intValue <= 0) { throw new IndexOutOfRangeException(); } String outputString = "[" + sequenceSelector + "]: "; for (int i = 0; i < intValue; i++) { outputString = outputString + fibonacciSequence.GetValue(i) + ", "; // you can omit the call to ToString, it´s called implictely by the runtime } Console.WriteLine(outputString); return intValue; } else if(sequenceSelector.ToUpper().Contains("STOP")) { ... }

{{1}}

答案 1 :(得分:2)

您需要首先检查&#34;停止&#34;包含在Console.ReadLine()返回的字符串中:

string input = Console.ReadLine();
if (input.ToUpper().Contains("STOP"))
    return; // or do something to leave the loop

// now you now it's not "stop" -> parse it
int sequenceSelector = Convert.ToInt32(input);

sequenceSelector.ToUpper()无法正常工作,因为sequenceSelectorint。即使它确实有效,结果也不会包含"stop""STOP"