C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: Semantically, ArgumentException indicates that a method was called with an invalid argument.
Constructor: When using the ArgumentNullException constructor, you can pass a string literal that is equal to the variable name that was null.
Tip: You can use the same pattern on ArgumentException, which indicates a general argument-related exception.
C# program that uses ArgumentException
using System;
class Program
{
static void Main()
{
// Demonstrate the argument null exception.
try
{
A(null);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
// Demonstrate the general argument exception.
try
{
A("");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
// Flow path without exception.
Console.WriteLine(A("test"));
}
static int A(string argument)
{
// Handle null argument.
if (argument == null)
{
throw new ArgumentNullException("argument");
}
// Handle invalid argument.
if (argument.Length == 0)
{
throw new ArgumentException("Zero-length string invalid", "argument");
}
return argument.Length;
}
}
Output: truncated
System.ArgumentNullException: Value cannot be null.
Parameter name: argument
at Program.A(String argument)...
System.ArgumentException: Zero-length string invalid
Parameter name: argument
at Program.A(String argument)...
4
Example: Maybe the method A would receive two strings, and neither of them could be validly null—the argument name would be helpful.
But: With an internal method, the arguments may not need to be carefully validated because they may never be invalid.
So: For truly performance-critical methods, do not validate arguments in most cases.
And: The indexer compiles to the get_Item method. Internally, get_Item eventually uses the statement "throw new ArgumentNullException".
C# program that causes ArgumentNullException
using System.Collections.Generic;
class Program
{
static void Main()
{
var dictionary = new Dictionary<string, int>();
int value = dictionary[null];
}
}
Output
Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: key
Tip: In many cases, avoiding the null check and allowing the runtime itself to detect a NullReferenceException would be faster.
Tip: Internally, Substring checks its argument for a negative value. With this exception, it alerts you to an invalid value.
And: This error is helpful. It makes your program easier to fix. It pinpoints the nature of your logical error.
Example: The ArgumentOutOfRangeException is thrown explicitly, with a throw statement, not by the runtime. The message helps you pinpoint the cause.
ThrowC# program that causes ArgumentOutOfRangeException
class Program
{
static void Main()
{
string value = "test".Substring(-1);
}
}
Output
Unhandled Exception:
System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
Parameter name: startIndex