3 回答

TA貢獻1835條經(jīng)驗 獲得超7個贊
永遠不要Convert.ToInt32在用戶輸入上使用。
使用Int.TryParse來代替。
這是一個令人煩惱的例外的完美例子。
令人煩惱的異常是不幸的設(shè)計決策的結(jié)果。惱人的異常是在完全非異常的情況下拋出的,因此必須一直被捕獲和處理。
令人煩惱的異常的經(jīng)典示例是 Int32.Parse,如果給它一個無法解析為整數(shù)的字符串,它就會拋出異常。但是此方法的 99% 用例是轉(zhuǎn)換用戶輸入的字符串,這可能是任何舊事物,因此解析失敗絕不是例外。
Convert.ToInt32接受字符串作為參數(shù)的重載只是int.Parse在內(nèi)部調(diào)用-請參閱它的源代碼:
public static int ToInt32(String value) {
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
因此它和使用一樣令人煩惱int.Parse,應(yīng)該避免。經(jīng)驗法則是不適合的東西,你可以很容易地通過檢查代碼中使用的例外-例外是特殊的東西-主要的東西,你不能在你的代碼控制,如網(wǎng)絡(luò)的可用性和類似的東西-與用戶輸入adsf的,而不是12IS一點也不例外。
直接回答您的問題,
您沒有捕獲異常的原因是因為您Convert.ToInt32不在try塊內(nèi)。
要真正捕獲異常,您的代碼應(yīng)該如下所示:
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);
}

TA貢獻1834條經(jīng)驗 獲得超8個贊
您的try塊沒有圍繞可能引發(fā)InvalidCastException. 試試這個:
Console.Write("Row (1-3): ");
int UserRowChoice;
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);
}

TA貢獻1860條經(jīng)驗 獲得超9個贊
在將值類型傳遞給您想要執(zhí)行的任何操作之前,請嘗試檢查該值類型。
string line = Console.ReadLine();
int value;
if (int.TryParse(line, out value))
{
Console.WriteLine("Integer here!");
}
else
{
Console.WriteLine("Not an integer!");
}
如果值是否為 int ,這將返回!如果它是一個int,繼續(xù)你想要的任何東西,否則,再次詢問使用。
- 3 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報