GetLastError Function

Declare Function GetLastError Lib "kernel32.dll" () As Long

Platforms

Description & Usage

GetLastError obtains the error code returned by the last API function called. Most API functions merely return a number saying if an error occured, but not specifying exactly which error occured. This function gets a universal error code identifying the type of error that last occured. Note that most functions set the code to 0 (success) if the function completes successfully, erasing the previous error code. Therefore, be sure to check this error code immediately after an error is found.

Return Value

The function returns the error code of the last API function called by the program.

Visual Basic-Specific Issues

Although GetLastError works perfectly in Visual Basic, it will sometimes not appear to work. This is because Visual Basic implicitly uses the API frequently to perform tasks which are seemingly intrinsic to the language. These hidden API function calls will usually overwrite the error code which your code may be trying to read. To compensate for this, the LastDllError property of the Err object, predefined in Visual Basic, caches the error code from the last API function explicitly called by your program. You should use the expression Err.LastDllError instead of the GetLastError function to debug failed API function calls.

Parameters

None.

Example

' This code is licensed according to the terms and conditions listed here.

' Demonstrate catching an invalid handle error.
' If this code does not work, try replacing "GetLastError()" with Err.LastDllError.
Dim retval As Long  ' return value of function
Dim errorcode As Long  ' error code

' Make an invalid call to the following function by giving it an invalid handle
retval = CloseHandle(-1)  ' there is no handle -1!
If retval = 0 Then  ' the return value will be 0 if an error occured
  errorcode = GetLastError()  ' find the error code
  If errorcode = 6 Then Debug.Print "ERROR: Invalid Handle Specified"  ' error 6 = invalid handle
End If

See Also

CommDlgExtendedError, SetLastError, SetLastErrorEx

Category

Errors

Go back to the alphabetical Function listing.
Go back to the Reference section index.


Last Modified: January 5, 2000
This page is copyright © 2000 Paul Kuliniewicz. Copyright Information Revised October 29, 2000
Go back to the Windows API Guide home page.
E-mail: vbapi@vbapi.com Send Encrypted E-Mail
This page is at http://www.vbapi.com/ref/g/getlasterror.html