演習 - チャレンジ アクティビティを完了して特定の例外をキャッチする

完了

このモジュールのコードチャレンジは、学習したことを補強し、続行する前に自信を持って得るのに役立ちます。

特定の例外をキャッチするチャレンジ

この課題では、いくつかの異なる例外の種類を生成するコード サンプルが提供されています。 1 つの 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.
    

がんばってください。