初學 try---catch 語法
try { 可能會出現異常的代碼; 異常出現的那行代碼下面的代碼全不會執行,直接跳到catch中執行 ... ... } //try和catch之間不能有其他的代碼 catch { 出現異常后要執行的代碼; }
技巧
Console.WriteLine("你的語文成績?"); int chainese = 0;//聲明變量再初始化賦值為0,因為在try中聲明作用域只能在try中的大括號中有效. bool chaineseExecption = true;//這是一個小技巧,異常執行catch中代碼並這個賦值變量為false //當輸入非數字字符串報異常處理辦法 try { chainese = int.Parse(Console.ReadLine());//接受的是非數字字符串異常 } catch { Console.WriteLine("你輸入的內容不能轉換成字符串"); chaineseExecption = false; // } if (chaineseExecption == true)//異常不執行的代碼 { if (chainese >= 90) { Console.WriteLine("語文成績{0}, 成績優秀獎勵100元RMB"); } else { Console.WriteLine("繼續努力希望下次你能考出好的成績"); } } Console.ReadKey();