VB .NET

Agilent VISA.NET

VB .NET

Error handling in .NET is implemented by exceptions.  However, you are using the VISA C DLL directly, and it returns error return codes rather than throwing exceptions.  One way to handle the errors is to observe the return code of each VISA call, then either return from the method or execute some cleanup code inside the if statement that checks the error.  Since .NET has excellent support for exceptions, you can use a simple utility function to turn the error codes into exceptions, and wrap your code in a try-catch block.

Below is a utility function for turning VISA errors into System.ApplicationException exceptions.  You may wish to create your own VISA exception class that derives from System.ApplicationException in order to better handle VISA errors.

VB .NET

Private Sub CheckStatus(ByVal vi As Integer, ByVal status As Integer)    If (status < visa32.VI_SUCCESS) Then        Dim err As System.Text.StringBuilder = New System.Text.StringBuilder(256)        visa32.viStatusDesc(vi, status, err)        Throw New ApplicationException(err.ToString())    End If End Sub

This method takes a valid VISA session and a VISA status code as arguments.  The session can be either the Resource Manager session or a VISA resource session; the error descriptions returned by viStatusDesc will be the same in either case.  The method will throw an exception with the error description if the status code is an error code, or do nothing otherwise.

You must wrap any code that calls this helper method in an exception handler, or a VISA error will cause your program to terminate.  Here is an example of how to use CheckStatus.

VB .NET

Dim status As Integer      'VISA function status return code Dim defrm As Integer       'Session to Default Resource Manager Dim vi As Integer          'Session to instrument status = visa32.viOpenDefaultRM(defrm) ' cannot check status on viOpenDefaultRM, since if this failed ' we don't have a valid vi to pass to CheckStatus Try    status = visa32.viOpen(defrm, "instrAddress", 0, 0, vi)    CheckStatus(defrm, status)    ' ... Catch err As System.ApplicationException    MsgBox("*** Error : " & err.Message, vbExclamation, _                        "VISA Error Message")    Exit Sub End Try ' ...

The Try block guarantees that any ApplicationException generated by CheckStatus will get caught in the Catch block, where an error dialog is displayed.

Next: Reading and Writing Array Data