練習 - 完成挑戰活動以攔截特定例外狀況

已完成

本課程模組中的程式代碼挑戰可用來強化您學到的內容,並協助您在繼續之前獲得一些信心。

捕捉特定例外狀況的任務

在此挑戰中,您會提供產生數種不同例外狀況類型的程式代碼範例。 單一程式 try 代碼區塊包含產生例外狀況的程序代碼。 包含多個 catch 子句來處理特定例外狀況類型。

您必須更新程式碼範例,以便攔截每個例外狀況,並將對應的錯誤訊息顯示至主控台。

以下是這項挑戰的需求:

  1. 請確定您的Program.cs檔案包含下列程式代碼範例:

    try
    {
        int num1 = int.MaxValue;
        int num2 = int.MaxValue;
        int result = num1 + num2;
        Console.WriteLine("Result: " + result);
    
        string str = null;
        int length = str.Length;
        Console.WriteLine("String Length: " + length);
    
        int[] numbers = new int[5];
        numbers[5] = 10;
        Console.WriteLine("Number at index 5: " + numbers[5]);
    
        int num3 = 10;
        int num4 = 0;
        int result2 = num3 / num4;
        Console.WriteLine("Result: " + result2);
    }
    catch (OverflowException ex)
    {
        Console.WriteLine("Error: The number is too large to be represented as an integer." + ex.Message);
    }
    catch (NullReferenceException ex)
    {
        Console.WriteLine("Error: The reference is null." + ex.Message);
    }
    catch (IndexOutOfRangeException ex)
    {
        Console.WriteLine("Error: Index out of range." + ex.Message);
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("Error: Cannot divide by zero." + ex.Message);
    }
    
    Console.WriteLine("Exiting program.");
    
  2. 更新程式代碼,以便在發生該例外狀況類型時,向主控台顯示每個錯誤訊息。

  3. 確認更新的程式代碼會將下列訊息列印至主控台:

    Error: The number is too large to be represented as an integer. Arithmetic operation resulted in an overflow.
    Error: The reference is null. Object reference not set to an instance of an object.
    Error: Index out of range. Index was outside the bounds of the array.
    Error: Cannot divide by zero. Attempted to divide by zero.
    Exiting program.
    

祝你好運!