Access Non-.NET APIs with PInvoke : VB.NET: Handle Exceptions Properly: Listing 1
When you call Windows API functions, they don't throw managed exceptions. Instead, you need to check their return values for any indication of an error, and take the appropriate actions, which might include throwing your own managed exception.
Dim phonebook As String _
= Nothing
Dim count As Int32 = 5
Dim entries(0 To count - 1) _
As RASENTRYNAME
Dim size = Marshal.SizeOf( _
GetType(RASENTRYNAME))
entries(0).Size = size
Dim buffersize = size * count
Dim rtn = RasEnumEntries(IntPtr.Zero, _
phonebook, _
entries, _
buffersize, _
count)
If rtn = _
RasErrorCodes. _
BUFFER_TOO_SMALL Then
'need to resize and
'call the function again
ReDim entries(0 To count - 1)
entries(0).Size = size
buffersize = size * count
rtn = RasEnumEntries(IntPtr.Zero, _
phonebook, _
entries, _
buffersize, _
count)
End If
Select Case rtn
Case _
RasErrorCodes. _
NOT_ENOUGH_MEMORY, _
RasErrorCodes. _
INVALID_SIZE
Throw New Exception( _
"RAS exception:" _
& rtn.ToString)
Case RasErrorCodes.SUCCESS
If count <> _
entries.Length Then
ReDim Preserve _
entries(0 To count - 1)
End If
Return entries
Case Else
Return Nothing
End Select