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?
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:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With