Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exception should be thrown for an invalid file name?

I have a method which accepts a filename as a parameter, all filenames should end with '.csv'. Which exception should I throw if a filename that does not end with .csv is passed?

Or should I take a different approach?

like image 642
Simon Avatar asked Sep 14 '09 13:09

Simon


1 Answers

ArgumentOutOfRangeException - What you're describing is in line with an out of range exception:

The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.

ArgumentException is used to validate the characters in the path string not the file type.

The path parameter is a zero-length string, contains only white space, or contains one or more invalid characters.

IMHO the path validation fall-through chart looks like this:

  • Input path is null = ArgumentNullException
  • Invalid characters in the path = ArgumentException
  • File doesn't exist = FileNotFoundException
  • File isn't the right type = ArgumentOutOfRangeException
  • Permissions problem = UnauthorizedAccessException
  • File system doesn't support this operation = NotSupportedException
  • System read error = IOException

If that's not descriptive enough for you then create your own exception class:

public class InvalidFileTypeException : System.IO.IOException
{
    public InvalidFileTypeException(string path, string acceptedTypeMask) 
    {
        this.Message = string.Format(
            "File type '{0}' does not fall within the expected range: '{1}'", 
            path, 
            acceptedTypeMask);
    }
}

...

throw new InvalidFileTypeException("foo.txt", "*.csv");
like image 101
xcud Avatar answered Sep 21 '22 12:09

xcud