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
comments powered by Disqus

Featured

  • Microsoft Highlights Visual Studio Live! Event Lineup and Longtime Developer Community Role

    A Microsoft MVP Blog post on Visual Studio Live!'s longevity arrives as the 2026 conference series continues with upcoming stops at Microsoft HQ, San Diego and Orlando.

  • Using Local AI to Cut Copilot Usage-Based Billing Shock

    After being gobsmacked by the new billing plan using almost all my monthly credits in one or two days, I tried pushing some Copilot-style coding work onto local models in VS Code. What I found was less "free AI" and more "pick your pain": cloud charges on one side, heavy local resource use and long waits on the other.

  • .NET 11 Preview 5 Focuses on Performance, Productivity and Safer Code

    .NET 11 Preview 5 focuses on under-the-hood runtime performance gains, streamlined APIs and language features that reduce boilerplate, plus built‑in security checks and incremental ASP.NET Core and EF Core improvements aimed at everyday developer productivity.

  • VS Code 1.124 Focuses on Agent Autonomy and Parallel Sessions

    Microsoft's June 2026 VS Code update turns on Autopilot by default and adds background sending for agent sessions.

Subscribe on YouTube