ArgumentException ExamplesLearn how to validate arguments to a Function with ArgumentException, and use ArgumentNullException ThrowIfNull.
This page was last reviewed on Nov 30, 2023.
ArgumentException. Suppose a function in your VB.NET program only works correctly when passed an argument that is not Nothing or empty. We can validate the argument with ArgumentException.
A helpful function. With ArgumentNullException, we can call a Function called ThrowIfNull. This reduces the code we need to write to validate arguments for Nothing.
Example. This program is designed to cause an ArgumentNullException and an ArgumentException. We use Try blocks to ensure the program continues running.
Step 1 To begin, we call the Test function with an argument of Nothing. The IsNothing call in Test returns true, so we throw an exception.
Step 2 The Test() function also can throw an ArgumentException if its argument is a string with length of zero.
String Length
Step 3 If we pass a valid string like "test" to the Test function, it returns normally and does not throw.
Module Module1 Function Test(argument As String) As Integer ' Throw ArgumentNullOrException, or ArgumentException, based on argument value. If IsNothing(argument) Throw New ArgumentNullException("argument") End If If argument.Length = 0 Throw New ArgumentException("Empty string", "argument") End If Return argument.Length End Function Sub Main() ' Step 1: cause ArgumentNullException. Try Test(Nothing) Catch ex As Exception Console.WriteLine(ex) End Try ' Step 2: cause ArgumentException. Try Test("") Catch ex As Exception Console.WriteLine(ex) End Try ' Step 3: no exception. Console.WriteLine(Test("test")) End Sub End Module
System.ArgumentNullException: Value cannot be null. (Parameter 'argument') at ... System.ArgumentException: Empty string (Parameter 'argument') at ... 4
ThrowIfNull. We can use ThrowIfNull if we want an ArgumentNullException for the argument. With this function, we can avoid writing a 3-line If-block.
Module Module1 Function Test(argument As String) As Integer ' Use ThrowIfNull. ArgumentNullException.ThrowIfNull(argument) Return 0 End Function Sub Main() Test(Nothing) End Sub End Module
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'argument') at System.ArgumentNullException.Throw(String paramName) at System.ArgumentNullException.ThrowIfNull(Object argument, String paramName) at ...
Summary. Even though Nothing is supposed to mean null in VB.NET, we still use the ArgumentNullException. Other ArgumentExceptions are also often encountered.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 30, 2023 (new).
© 2007-2024 Sam Allen.