Menu
Coddy logo textTech

Error Handling

Part of the Logic & Flow section of Coddy's C# journey — lesson 45 of 66.

challenge icon

Challenge

Easy

Let's enhance our system with robust error handling to deal with potential issues gracefully. Create a class called ErrorHandler with these methods:

  1. ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex): Validates the input indices and returns an appropriate error message or an empty string if valid.
    • Returns "Invalid student index" if the student index is out of bounds.
    • Returns "Invalid assignment index" if the assignment index is out of bounds.
    • Returns an empty string "" if both indices are valid.
  2. SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex): Safely retrieves a score with error handling.
    • Returns the score if both indices are valid.
    • Returns -999 if any index is invalid.
  3. ProcessBatchUpdate(int[][] scoreGrid, int[][] updates): Processes batch updates where each update is [studentIndex, assignmentIndex, score].
    • Returns a string[] array of error messages for each failed update.
    • Each update can fail with one of these specific error messages:
      • "Invalid update format" — if the update does not contain exactly 3 values.
      • "Invalid student index" — if the student index is out of bounds.
      • "Invalid assignment index" — if the assignment index is out of bounds.
      • "Invalid score value" — if the score is outside the valid range (0–100).
    • Format each error as: "Error at index X: [specific error message]"
    • Return an empty array if all updates are successful.
Hint: To collect errors dynamically before returning them as a string[], use List<string> errors = new List<string>();List<string> works like a resizable array where you can call errors.Add(...) to append items. At the end, convert it with errors.ToArray(). The using System.Collections.Generic; import needed for this is already included at the top of the file.

Try it yourself

using System; // Don't delete this line
using System.Collections.Generic;

public class ErrorHandler
{
    public static string ValidateInput(int[][] scoreGrid, int studentIndex, int assignmentIndex)
    {
        // Write your code here
        
    }
    
    public static int SafeGetScore(int[][] scoreGrid, int studentIndex, int assignmentIndex)
    {
        // Write your code here
        
    }
    
    public static string[] ProcessBatchUpdate(int[][] scoreGrid, int[][] updates)
    {
        // Write your code here
        
    }
}

// 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)
    {
        // Check for out of bounds indices
        if (studentIndex < 0 || studentIndex >= scoreGrid.Length || 
            assignmentIndex < 0 || assignmentIndex >= scoreGrid[studentIndex].Length)
        {
            return -1;
        }
        
        // Validate the score
        if (!DataCollector.ValidateScore(score))
        {
            return -2;
        }
        
        // Set the score
        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)
    {
        // Check if student index is valid
        if (studentIndex < 0 || studentIndex >= scoreGrid.Length)
        {
            return -1;
        }
        
        int sum = 0;
        int count = 0;
        
        // Calculate sum of valid scores
        for (int j = 0; j < scoreGrid[studentIndex].Length; j++)
        {
            int score = scoreGrid[studentIndex][j];
            if (score != -1)  // Ignore ungraded assignments
            {
                sum += score;
                count++;
            }
        }
        
        // Return average or 0 if no valid scores
        return count > 0 ? (double)sum / count : 0;
    }
    
    public static double CalculateAssignmentAverage(int[][] scoreGrid, int assignmentIndex)
    {
        // Check if there are any students
        if (scoreGrid.Length == 0)
        {
            return -1;
        }
        
        // Check if assignment index is valid
        if (assignmentIndex < 0 || assignmentIndex >= scoreGrid[0].Length)
        {
            return -1;
        }
        
        int sum = 0;
        int count = 0;
        
        // Calculate sum of valid scores for the assignment
        for (int i = 0; i < scoreGrid.Length; i++)
        {
            if (assignmentIndex < scoreGrid[i].Length)
            {
                int score = scoreGrid[i][assignmentIndex];
                if (score != -1)  // Ignore ungraded assignments
                {
                    sum += score;
                    count++;
                }
            }
        }
        
        // Return average or 0 if no valid scores
        return count > 0 ? (double)sum / count : 0;
    }
    
    public static int[] FindHighestScore(int[][] scoreGrid)
    {
        int highestStudentIndex = 0;
        int highestAssignmentIndex = 0;
        int highestScore = -1;
        
        // Search for the highest score
        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 };
    }
}

All lessons in Logic & Flow