gpt4 book ai didi

c# - 为什么这没有捕捉到错误

转载 作者:行者123 更新时间:2023-12-03 09:02:59 25 4
gpt4 key购买 nike

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

3年前关闭。




Improve this question




当用户输入字符串而不是整数时,它会给我和错误并使控制台崩溃。我不明白如何捕捉这个错误。如果发生此错误,我希望它做的是跳过玩家的回合。

Console.Write("Row (1-3): ");
int UserRowChoice = Convert.ToInt32(Console.ReadLine());
try { }
catch (InvalidCastException e) { ThrowError("You typed a string instead of an integer. You've lost your turn."); Console.ReadKey(); RunGame(T1, CurrentPlayer, Winner); }
if (UserRowChoice < 1 || UserRowChoice > 3)
{
ThrowError("You either typed a number that was less than 1 or greater than 3. You've lost your turn.");
Console.ReadKey();
RunGame(T1, CurrentPlayer, Winner);
}

最佳答案

切勿使用 Convert.ToInt32关于用户输入。
使用Int.TryParse反而。
这是 vexing exception. 的完美示例

Vexing exceptions are the result of unfortunate design decisions. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.

The classic example of a vexing exception is Int32.Parse, which throws if you give it a string that cannot be parsed as an integer. But the 99% use case for this method is transforming strings input by the user, which could be any old thing, and therefore it is in no way exceptional for the parse to fail.

Convert.ToInt32接受字符串作为参数的重载只需调用 int.Parse里面 - see it's source code:
public static int ToInt32(String value) {
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
因此它就像使用 int.Parse 一样令人烦恼。并且应该避免。
经验法则是不要将异常用于您可以使用代码轻松检查的事情 - 异常用于异常事情 - 主要是您无法在代码中控制的事情,例如网络可用性和类似的事情 - 以及用户输入 adsf而不是 12一点也不异常(exception)。
直接回答你的问题,
您没有捕获异常的原因是因为您的 Convert.ToInt32不在您的 try 内堵塞。
要真正捕获异常,您的代码应该如下所示:
Console.Write("Row (1-3): ");
int UserRowChoice = 0;
try
{
UserRowChoice = Convert.ToInt32(Console.ReadLine());
}
catch (InvalidCastException e) { ThrowError("You typed a string instead of an integer. You've lost your turn."); Console.ReadKey(); RunGame(T1, CurrentPlayer, Winner); }
if (UserRowChoice < 1 || UserRowChoice > 3)
{
ThrowError("You either typed a number that was less than 1 or greater than 3. You've lost your turn.");
Console.ReadKey();
RunGame(T1, CurrentPlayer, Winner);
}
但是,正如我之前写的,不要使用 Convert.ToInt32 - 使用 int.TryParse反而:
Console.Write("Row (1-3): ");
int UserRowChoice = 0;
if(int.TryParse(Console.ReadLine(), out UserRowChoice))
{
if (UserRowChoice < 1 || UserRowChoice > 3)
{
ThrowError("You either typed a number that was less than 1 or greater than 3. You've lost your turn.");
Console.ReadKey();
RunGame(T1, CurrentPlayer, Winner);
}
}
else
{
ThrowError("You typed a string instead of an integer. You've lost your turn.");
Console.ReadKey();
RunGame(T1, CurrentPlayer, Winner);
}

关于c# - 为什么这没有捕捉到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com