Skip to content

ZH TW CSharp Keyword try

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: try

使用手冊C# · 實用指南

包圍其異常由 catch 處理或後接 finally 的操作。

簡單範例 (Example.cs)

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

Example.cs:

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

結果:

Invalid

句法

try { ... } catch (...) { ... } finally { ... }

例1:基本形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        try { int number = int.Parse("invalid"); Console.WriteLine(number); }
        catch (FormatException error) { Console.WriteLine(error.Message); }
        finally { Console.WriteLine("Finished"); }
    }
}

例2:另一種實用形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        try { Validation.Positive(-1); }
        catch (ArgumentOutOfRangeException error) when (error.ParamName == "value") { Console.WriteLine("Negative value"); }
        finally { Console.WriteLine("Cleanup"); }
    }
}
public static class Validation { public static void Positive(int value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); } }

官方來源:Microsoft學習。

Clone this wiki locally