程式碼嘗試將變數 score(初始為空字串 "")轉換為 int,拋出 System.FormatException。
string score = "";
// ... 未賦值直接轉換
int a = Convert.ToInt16(score); // 拋出異常
Convert.ToInt16("")、int.Parse("") 皆會拋出 FormatException,因為空字串非有效數字格式。
string score = "0"; 或宣告時給預設值。if (string.IsNullOrEmpty(score)) score = "0";
int a = int.TryParse(score, out int result) ? result : 0;
int.TryParse 避免例外開銷。