Alert the User if aqawords.txt File is Missing

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

A Simple solution to this issue:

static void Main(string[] args)
        {
            if (!File.Exists("aqawords.txt"))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Dictionary doesn't exsist, please replace file");
            }

}


This simply checks to see if the file exists, if it doesn't it prints a red error message to the user.



This is actually not as difficult as it may first appear. Firstly, let's take a glimpse at the LoadAllowedWords method which actually loads the contents of the AQAwords.txt file.

private static void LoadAllowedWords(ref List<string> AllowedWords) {
    try {
        StreamReader FileReader = new StreamReader("aqawords.txt");

        while (!FileReader.EndOfStream) {
            AllowedWords.Add(FileReader.ReadLine().Trim().ToUpper());
        }

        FileReader.Close();
    } catch (Exception) {
        AllowedWords.Clear();
    }
}

The entire method is wrapped in a try/catch statement, meaning if we create a new handler for a FileNotFoundException (which is thrown if a file isn't found) then we can easily alert the player.

private static void LoadAllowedWords(ref List<string> AllowedWords) {
    try {
        StreamReader FileReader = new StreamReader("aqawords.txt");

        while (!FileReader.EndOfStream) {
            AllowedWords.Add(FileReader.ReadLine().Trim().ToUpper());
        }

        FileReader.Close();

    } catch (FileNotFoundException) {
        Console.WriteLine($"File 'aqawords.txt' not found");
        AllowedWords.Clear(); // Also needs to be done
    } catch (Exception) { 
        AllowedWords.Clear();
    }
}

Done, that's all u need to do to alert the player. Now seeing as the game is unplayable we should by all rights end it here, but seeing as that's out of the perview of the task I'll leave it as is. I feel I should also note, exception handlers are executed in order of inheritance from the highest parent down. Thus if the new catch statement we've placed was put after the "catch (Exception)" block then it would be unreachable and never run. REMEMBER all exceptions inherit from the root parent class 'Exception', hence the "catch (Exception)" will be executed for ALL exceptions thrown regardless if the next checked exception down the line is a closer match to the actual thrown exception.