例外為執行期錯誤,C# 透過 Exception 基底類別處理。可自訂例外類別,但必須繼承 Exception。內建例外 (如 IndexOutOfRangeException) 可直接捕捉;非內建情境需自訂。
using System;
public class MyException : Exception
{
public string s;
public MyException() : base() { s = null; }
public MyException(string message) : base() { s = message; }
public MyException(string message, Exception inner) : base(message, inner) { s = message; }
public static void Test()
{
string str, msg = null;
bool flag = false;
char ch = ' ';
int i = 0;
Console.Write("請輸入字串 (少於 27 字元) - ");
str = Console.ReadLine();
try
{
ch = str[i];
while (!flag)
{
if (ch == '\r') flag = true;
else { ch = str[i]; i++; }
}
}
catch (Exception) { flag = true; }
if (i > 27)
{
msg = "您的輸入不能超過 27 個字元!";
throw new MyException(msg);
}
}
public static void Main()
{
try { Test(); }
catch (MyException e) { Console.WriteLine(e.s); }
}
}
Main 的 catch 區塊捕獲並顯示訊息