try/catch阻止功能限制

Har*_*rry 0 c# try-catch

我希望程序的用户能够重复操作,直到他们通过输入某个字符串来指示程序停止运行.我试图通过使用以下命令输入单词"stop"来允许用户停止程序:

If (sequenceSelector.ToUpper().Contains("stop"))    
{
    //code to do stuff here
}
Run Code Online (Sandbox Code Playgroud)

目前,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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Him*_*ere 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")) { ... }
Run Code Online (Sandbox Code Playgroud)