Search code examples
c#exceptionerror-handlingguard-clause

Guard Clause and Exception handling for the same condition


I ran across the following snippet of code. Names have been changed to protect the innocent:

    public void RunProgram()
    {
        System.IO.FileInfo fInfo = new System.IO.FileInfo(Application.StartupPath + "Program.exe");

        if (!fInfo.Exists)
        {
            System.Windows.Forms.MessageBox.Show("Program could not be found, please verify your installation.\n\nDetails:\n" + fInfo.FullName);
            return;
        }

        try
        {
            System.Diagnostics.Process  process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo pStart  = new System.Diagnostics.ProcessStartInfo(); 
            pStart.FileName = fInfo.FullName;
            pStart.UseShellExecute = true;
            process.StartInfo = pStart;
            process.Start();
        }
        catch
        {
            System.Windows.Forms.MessageBox.Show(string.Format("An error occurred trying to run the program:{0}", fInfo.FullName));
        }
    }

I know there are a few things wrong here:

  • Exception types aren't being handled individually
  • Error message isn't informative enough

Rest assured I'll be addressing those as well but my main question is about the check for the file's existence just before the try/catch block. This strikes me as a bit redundant.

The point of exception handling is to catch unexpected conditions. I fully expect the file to be there so removing the existence check and just letting the exception handling catch it if it isn't seams a reasonable solution to me.

What do you think?


Solution

  • It is redundant and may give a false sense of security. Please note that you could still get a FileNotFound exception due to concurrency.

    Also see: Is there a case where parameter validation may be considered redundant?