如何使用 try/catch 處理例外狀況

try-catch 區塊的目的是為了攔截和處理工作程式碼所產生的例外狀況。 某些例外狀況可在 catch 區塊中處理,而問題已解決且未再次擲回例外狀況;不過,有更多時候您唯一能做的事是確保會擲回適當的例外狀況。

範例

在此範例中,IndexOutOfRangeException 不是最適當的例外狀況:ArgumentOutOfRangeException 更適用於此方法,因為錯誤是由呼叫者傳入的 index 引數所導致。

static int GetInt(int[] array, int index)
{
    try
    {
        return array[index];
    }
    catch (IndexOutOfRangeException e)  // CS0168
    {
        Console.WriteLine(e.Message);
        // Set IndexOutOfRangeException to the new exception's InnerException.
        throw new ArgumentOutOfRangeException("index parameter is out of range.", e);
    }
}

註解

造成例外狀況的程式碼位於 try 區塊中。 緊接在後面新增的 catch 陳述式可處理所發生的 IndexOutOfRangeExceptioncatch 區塊會處理 IndexOutOfRangeException,然後改為擲回更適當的 ArgumentOutOfRangeException。 為了盡可能為呼叫者提供更多資訊,請考慮將原始的例外狀況指定為新例外狀況的 InnerException。 因為 InnerException 屬性為 read-only,所以您必須在新例外狀況的建構函式中指派此屬性。