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
.
With ArgumentNullException
, we can call a Function called ThrowIfNull
. This reduces the code we need to write to validate arguments for Nothing.
This program is designed to cause an ArgumentNullException
and an ArgumentException
. We use Try blocks to ensure the program continues running.
IsNothing
call in Test returns true, so we throw an exception.Test()
function also can throw an ArgumentException
if its argument is a string
with length of zero.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 ...
Even though Nothing is supposed to mean null
in VB.NET, we still use the ArgumentNullException
. Other ArgumentExceptions
are also often encountered.