Skip to content

ZH TW CSharp Exceptions

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

異常,try/catch/finally 和 throw

手冊C# · 範例UO

try 限制受保護區域,catch 處理適當的異常,finally 在退出時進行清理。過濾器when選擇一個處理程序。 throw; 重新拋出當前異常,保留原始堆疊; throw exception;改變了開頭。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
try { int.Parse("not a number"); }
catch (System.FormatException) { System.Console.WriteLine("Invalid"); }

結果:

Invalid
try
{
    int value = int.Parse("not a number");
    UO.Print(value.ToString());
}
catch (FormatException error)
{
    UO.Print(error.Message);
}
finally
{
    // Dispose resources owned by this scope.
}
int RequirePositive(int value)
{
    if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value));
    return value;
}
UO.Print(RequirePositive(3).ToString());

不要在沒有結束腳本的意圖的情況下攔截取消。清潔應該釋放自己的資源;取消對 finally 的遊戲呼叫可能會再次引發異常。編譯錯誤是在執行之前檢測到的,並且不是try執行程式碼中的正常錯誤。

官方文件:異常、try/catch/finally 和 throw - Microsoft Learn。

Clone this wiki locally