Exception Types
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 24/66。
C# では、例外はそれらが表すエラーに基づいて異なる種類に分類されます。これらの種類を理解することで、エラーをより効果的に処理できます。
一般的な例外の種類を見てみましょう:
すべての例外の基底クラスは System.Exception です。
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle any exception
Console.WriteLine(ex.Message);
}いくつかの一般的な例外の種類:
ArgumentException: メソッドが無効な引数で呼び出されたときにスローされます。
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException: null 参照のメンバーにアクセスしようとしたときにスローされます。
string text = null;
// This will throw NullReferenceException
int length = text.Length;IndexOutOfRangeException: 配列の範囲外のインデックスが指定されたときにスローされます。
int[] numbers = { 1, 2, 3 };
// This will throw IndexOutOfRangeException
int value = numbers[5];DivideByZeroException: 整数を 0 で割ろうとしたときにスローされます。
int result = 10 / 0; // DivideByZeroException がスローされます特定の例外をキャッチできます:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}チャレンジ
簡単ProcessArray という名前のメソッドを作成してください。このメソッドは:
- 整数配列とインデックスをパラメータとして受け取る
- 指定されたインデックスの要素にアクセスしようとする
- 成功した場合、要素の値を返す
IndexOutOfRangeExceptionが発生した場合、それをキャッチして -1 を返す
メソッドのシグネチャは以下のようであるべきです:
public static int ProcessArray(int[] array, int index)チートシート
すべての例外の基底クラスは System.Exception です:
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle any exception
Console.WriteLine(ex.Message);
}一般的な例外の種類:
ArgumentException:メソッドが無効な引数で呼び出されたときにスローされます:
string name = null;
if (name == null)
{
throw new ArgumentException("Name cannot be null");
}NullReferenceException:null 参照のメンバーにアクセスしようとしたときにスローされます:
string text = null;
int length = text.Length; // Throws NullReferenceExceptionIndexOutOfRangeException:配列のインデックスが範囲外の場合にスローされます:
int[] numbers = { 1, 2, 3 };
int value = numbers[5]; // Throws IndexOutOfRangeExceptionDivideByZeroException:整数を 0 で割ろうとしたときにスローされます:
int result = 10 / 0; // Throws DivideByZeroException特定の例外をキャッチする:
try
{
int[] numbers = { 1, 2, 3 };
int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}自分で試してみよう
using System;
class Program
{
public static int ProcessArray(int[] array, int index)
{
// ここにコードを記述してください
return 0;
}
static void Main(string[] args)
{
// 配列の入力を読み取る
string input = Console.ReadLine();
// 括弧が存在する場合は削除する
if (input.StartsWith("[") && input.EndsWith("]"))
{
input = input.Substring(1, input.Length - 2);
}
string[] parts = input.Split(',');
int[] array = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
array[i] = int.Parse(parts[i].Trim());
}
// インデックスの入力を読み取る
int index = int.Parse(Console.ReadLine());
int result = ProcessArray(array, index);
Console.WriteLine(result);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety