ArgumentException Throwing Guidelines
Please read this first: About Dave’s ‘unofficial’ Framework Design Guidelines.
þ DO throw ArgumentException or one of its subtypes for preventable errors.
For example, passing a null reference (Nothing in Visual Basic, nullptr in C++/CLI) for an argument when a value is expected, is an error that could have been prevented by a simple check for null by the caller.
The following method correctly throws an ArgumentNullException and ArgumentException for errors that are both preventable by the caller.
public void WriteToStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream"); // Correct
if (!stream.CanWrite)
throw new ArgumentException("'stream' must be writable.", "stream"); // Correct
// Use stream
}
ý DO NOT throw ArgumentException or one of its subtypes from a method for unpreventable errors or where prevention would be as expensive as calling the method itself.
For example, the following method incorrectly throws an ArgumentException for an error that the user is unable to prevent without replicating the same check that the method is performing internally.
public int GetSettingAsInt32(string name)
{
string value = GetSetting(name);
int result;
if (!int.TryParse(value, out result))
throw new ArgumentException(name + " cannot be represented as a Int32.", "name"); // Incorrect
return result;
}
Instead, a FormatException would be more appropriate.
public int GetSettingAsInt32(string name)
{
string value = GetSetting(name);
int result;
if (!int.TryParse(value, out result))
throw new FormatException(name + " cannot be represented as a Int32."); // Correct
return result;
}
ý DO NOT throw ArgumentException or one of its subtypes if you expect users to catch the exception.
ArgumentException is an indication of a broken contract, and when thrown, should indicate a bug in the calling code. Users should not be forced to catch ArgumentException or one of its subtypes.
For example, the following shows a method that incorrectly throws an ArgumentException to indicate that the server specified by the serverName parameter could not be found.
public void ConnectToServer(string serverName)
{
if (!TryConnect(serverName))
throw new ArgumentException("Unable to contact " + serverName, "serverName"); // Incorrect
}
Instead, as this is an error that user is likely to want to handle, ConnectToServer should throw an appropriate existing exception or a custom exception to indicate that it could not connect to the server.
public void ConnectToServer(string serverName)
{
if (!TryConnect(serverName))
throw new ServerNotFoundException("Unable to contact " + serverName); // Correct
}
Related Framework Design Guidelines Section: 7.3.4 ArgumentException, ArgumentNullException and ArgumentOutOfRangeException