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.
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 ModuleSystem.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 ModuleUnhandled 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.