try
{
// 可能拋出異常的代碼
}
catch (SpecificException ex)
{
// 處理特定異常
}
catch (Exception ex)
{
// 捕獲所有其他異常(放最後)
}
using System;
class MainClass
{
static void ProcessString(string str)
{
if (str == null)
throw new ArgumentNullException();
}
static void Main()
{
Console.WriteLine("輸出結果為:");
try
{
string str = null;
ProcessString(str);
}
catch (ArgumentNullException e)
{
Console.WriteLine("{0} First exception.", e.Message);
}
catch (Exception e)
{
Console.WriteLine("{0} Second exception.", e.Message);
}
}
}
ArgumentNullException 繼承自 Exception,必須先捕獲子類別。catch { } 等同 catch (Exception) { },但無法存取異常物件。Exception 掩蓋預期外錯誤。throw; 重拋原異常,throw ex; 會重設堆疊追蹤導致除錯困難。