← 從零開始學 C#
第 39 課,共 39 課 · 10 XP
例外
理論與題目說明
機器翻譯,尚未經母語人士審閱。
程式執行時發生的錯誤叫做例外。沒有人攔截的話,它會讓程式停止:
Unhandled exception. System.FormatException: The input string 'abc' was not in a correct format.
用 try / catch 攔截:
try
{
int n = int.Parse(input);
Console.WriteLine(100 / n);
}
catch (FormatException)
{
Console.WriteLine("不是數字");
}
catch (DivideByZeroException e)
{
Console.WriteLine("錯誤: " + e.Message);
}
finally
{
Console.WriteLine("一定會執行"); // 關閉檔案、釋放資源
}
自己的例外用 throw 拋出:
if (age < 0)
throw new ArgumentException("年齡不能是負數");
catch區塊依序檢查——具體的型別要放在一般的catch (Exception)前面;- 不要默默吞掉錯誤(
catch { })——不然永遠不會知道哪裡壞了; - 錯誤是可預期的情況時(使用者什麼都可能輸入),不用例外比較簡單:
int.TryParse(s, out int n)會回傳false。
題目。 對輸入中每一行 a b,輸出 a / b(整數除法)。行裡有不是數字的東西時輸出
錯誤:不是數字,b = 0 時輸出 錯誤:除以零。最後輸出 完成。使用 try / catch。