Error Handling
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 45/66。
チャレンジ
簡単システムを強化し、潜在的な問題を優雅に処理するための堅牢なエラーハンドリングを追加しましょう。ErrorHandler というクラスを作成し、次のメソッドを実装してください:
ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex):入力インデックスを検証し、有効な場合は適切なエラーメッセージまたは空文字列を返します。- 学生インデックスが範囲外の場合に
"Invalid student index"を返します。 - 課題インデックスが範囲外の場合に
"Invalid assignment index"を返します。 - 両方のインデックスが有効な場合に空文字列
""を返します。
- 学生インデックスが範囲外の場合に
SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex):エラーハンドリング付きで安全にスコアを取得します。- 両方のインデックスが有効な場合にスコアを返します。
- いずれかのインデックスが無効な場合に
-999を返します。
ProcessBatchUpdate(int[][] scoreGrid, int[][] updates):各更新が[studentIndex, assignmentIndex, score]であるバッチ更新を処理します。- 各失敗した更新に対するエラーメッセージの
string[]配列を返します。 - 各更新は、次の特定のエラーメッセージのいずれかで失敗する可能性があります:
"Invalid update format"— 更新に正確に 3 つの値が含まれていない場合。"Invalid student index"— 学生インデックスが範囲外の場合。"Invalid assignment index"— 課題インデックスが範囲外の場合。"Invalid score value"— スコアが有効範囲(0–100)外の場合。
- 各エラーを次の形式でフォーマットします:
"Error at index X: [specific error message]" - すべての更新が成功した場合に空配列を返します。
- 各失敗した更新に対するエラーメッセージの
string[] として返す前にエラーを動的に収集するには、List<string> errors = new List<string>(); を使用してください — List<string> はサイズ変更可能な配列のように動作し、errors.Add(...) を呼び出して項目を追加できます。最後に errors.ToArray() で変換します。このために必要な using System.Collections.Generic; のインポートはファイルの先頭に既に含まれています。自分で試してみよう
using System; // この行を削除しないでください
using System.Collections.Generic;
public class ErrorHandler
{
public static string ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex)
{
// ここにコードを書いてください
}
public static int SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex)
{
// ここにコードを書いてください
}
public static string[] ProcessBatchUpdate(int[][] scoreGrid, int[][] updates)
{
// ここにコードを書いてください
}
}
// Required for testing - do not modify
public class DataCollector
{
public static int[][] CreateScoreGrid(int students, int assignments)
{
int[][] scoreGrid = new int[students][];
for (int i = 0; i < students; i++)
{
scoreGrid[i] = new int[assignments];
}
return scoreGrid;
}
public static bool ValidateScore(int score)
{
return score >= 0 && score <= 100;
}
public static int[][] PopulateWithDefaultValues(int[][] scoreGrid)
{
for (int i = 0; i < scoreGrid.Length; i++)
{
for (int j = 0; j < scoreGrid[i].Length; j++)
{
scoreGrid[i][j] = -1;
}
}
return scoreGrid;
}
}
public class DataEntry
{
public static int SetStudentScore(int[][] scoreGrid, int studentIndex, int assignmentIndex, int score)
{
// 境界外のインデックスをチェック
if (studentIndex < 0 || studentIndex >= scoreGrid.Length ||
assignmentIndex < 0 || assignmentIndex >= scoreGrid[studentIndex].Length)
{
return -1;
}
// スコアを検証
if (!DataCollector.ValidateScore(score))
{
return -2;
}
// スコアを設定
scoreGrid[studentIndex][assignmentIndex] = score;
return 0;
}
public static int UpdateAllScores(int[][] scoreGrid, int[] studentIndices, int assignmentIndex, int score)
{
int successCount = 0;
for (int i = 0; i < studentIndices.Length; i++)
{
int result = SetStudentScore(scoreGrid, studentIndices[i], assignmentIndex, score);
if (result == 0)
{
successCount++;
}
}
return successCount;
}
}
public class DataAnalyzer
{
public static double CalculateStudentAverage(int[][] scoreGrid, int studentIndex)
{
// 学生インデックスが有効かどうかをチェック
if (studentIndex < 0 || studentIndex >= scoreGrid.Length)
{
return -1;
}
int sum = 0;
int count = 0;
// 有効なスコアの合計を計算
for (int j = 0; j < scoreGrid[studentIndex].Length; j++)
{
int score = scoreGrid[studentIndex][j];
if (score != -1) // 未採点の課題を無視
{
sum += score;
count++;
}
}
// 有効なスコアがない場合は平均または 0 を返します
return count > 0 ? (double)sum / count : 0;
}
public static double CalculateAssignmentAverage(int[][] scoreGrid, int assignmentIndex)
{
// 学生がいるかどうかをチェック
if (scoreGrid.Length == 0)
{
return -1;
}
// 課題インデックスが有効かどうかをチェック
if (assignmentIndex < 0 || assignmentIndex >= scoreGrid[0].Length)
{
return -1;
}
int sum = 0;
int count = 0;
// その課題の有効なスコアの合計を計算
for (int i = 0; i < scoreGrid.Length; i++)
{
if (assignmentIndex < scoreGrid[i].Length)
{
int score = scoreGrid[i][assignmentIndex];
if (score != -1) // 未採点の課題を無視
{
sum += score;
count++;
}
}
}
// 有効なスコアがない場合は平均または 0 を返します
return count > 0 ? (double)sum / count : 0;
}
public static int[] FindHighestScore(int[][] scoreGrid)
{
int highestStudentIndex = 0;
int highestAssignmentIndex = 0;
int highestScore = -1;
// 最高スコアを検索
for (int i = 0; i < scoreGrid.Length; i++)
{
for (int j = 0; j < scoreGrid[i].Length; j++)
{
int currentScore = scoreGrid[i][j];
if (currentScore > highestScore)
{
highestScore = currentScore;
highestStudentIndex = i;
highestAssignmentIndex = j;
}
}
}
return new int[] { highestStudentIndex, highestAssignmentIndex, highestScore };
}
}ロジックとフローのすべてのレッスン
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 Handling8Data Analysis System
Data Collection SetupData Entry Logic3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety