SetLastError Function

Declare Sub SetLastError Lib "kernel32.dll" (ByVal dwErrCode As Long)

Platforms

Description & Usage

SetLastError sets the API function error code for the calling thread. This error code is usually used to give a more detailed description of an error rather than a simple failure notification. The error code set by this function persists either until the next call to SetLastError or SetLastErrorEx or until another API function sets the error code from its operations (almost all of them call SetLastError internally).

Return Value

SetLastError does not return a value.

Visual Basic-Specific Issues

None.

Parameters

dwErrCode
The error code of the error to report. If your define your own error codes for use in your program, be sure that bit 29 (&H20000000) in it is set. Bit 29 denotes an application-defined error code; no error codes used by Windows have that bit set.

Example

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

' Use SetLastError to test the failure condition for another
' API function.  By setting the API error code, the error handling
' code can be run by simulating an actual error.
Dim retval As Long  ' return value

' Get the attributes of the file C:\autoexec.bat.
retval = GetFileAttributes("C:\autoexec.bat")

' Now "fake" a File Not Found error by setting the returned value to
' zero and setting the API error code to the proper value.
' (Obviously, these two lines would be removed after testing
' the error handler routine.)
retval = 0  ' make it look like the function failed
SetLastError ERROR_FILE_NOT_FOUND

' Now try to trap for the error.
If retval = 0 Then  ' some error occured
  Select Case Err.LastDllError  ' see the GetLastError page for usage of this
  Case ERROR_FILE_NOT_FOUND  ' File Not Found
    Debug.Print "The specified file could not be found."
  Case Else  ' ???
    Debug.Print "An unknown and untrapped error occured."
  End Select
Else
  Debug.Print "The function call was successful."
End If

See Also

GetLastError, SetLastErrorEx

Category

Errors

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


Last Modified: January 6, 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/s/setlasterror.html