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?
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?
I'd probably use ArgumentException, as it's "The exception that is thrown when one of the arguments provided to a method is not valid"
System.ArgumentException
appears appropriate, either directly or as a base class for your exception.
Check the documentation of an existing IO method in the Framework. It describes the exceptions generated by a method. For example, check StreamWriter.StreamWriter(String, Boolean, Encoding, Int32) Constructor at http://msdn.microsoft.com/en-us/library/0wf7ab94%28VS.85%29.aspx. The exception I suggest you use, to remain consistent, is IOException. You can then add a custom message that describes the particulars.
IOException - path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax.
In your case, the file extension is incorrect, so tell the user, as in Throw New IOException("Invalid file extension.")
.
I would leave ArgumentException as described in the documentation, path is an empty string ("")."
See Choosing the Right Type of Exception to Throw at http://msdn.microsoft.com/en-us/library/ms229021.aspx.
How about just creating your own InvalidFilenameException
? For example:
public class InvalidFilenameException : Exception
{
public string Filename { get; private set; }
public InvalidFilenameException(string message, string invalidFilename)
:base(message)
{
Filename = invalidFilename;
}
}
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");