在使用像 ExtractShortPathName
这样的 Windows API 函数包装器后调用 GetLastError
,我注意到无论调用 ExtractShortPathName
成功或失败,GetLastError
都返回一个非零错误代码。实际上,在我的程序执行之前似乎已经存在一个“上一个错误”,例如:
program TestGetLastError;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
var
ErrorCode: Integer;
begin
try
ErrorCode := GetLastError;
if ErrorCode <> 0 then
RaiseLastOSError;
except
on E: Exception do
WriteLn(E.ClassName, ': ', E.Message);
end;
end.
结果是:
EOSError: System Error. Code: 122.
The data area passed to a system call is too small
我是否有什么误解或做错了什么?
如果Delphi运行时执行某些操作导致设置了GetLastError
,那么在程序开始执行之前清除该错误的正确方法是什么?我应该像Delphi API文档中的示例一样使用SetLastError(ERROR_SUCCESS);
吗?
procedure TForm2.btRaiseLastClick(Sender: TObject);
begin
{ Set the last OS error to a bogus value. }
System.SetLastError(ERROR_ACCESS_DENIED);
try
RaiseLastOSError();
except
on Ex : EOSError do
MessageDlg('Caught an OS error with code: ' + IntToStr(Ex.ErrorCode), mtError, [mbOK], 0);
end;
{ Let the Delphi Exception dialog appear. }
RaiseLastOSError(ERROR_NOT_ENOUGH_MEMORY);
{ Finally set the last error to none. }
System.SetLastError(ERROR_SUCCESS);
if GetLastError() <> ERROR_SUCCESS then
MessageDlg('Whoops, something went wrong in the mean time!', mtError, [mbOK], 0);
{ No exception should be thrown here because last OS error is "ERROR_SUCCESS". }
CheckOSError(GetLastError());
end;
http://docwiki.embarcadero.com/CodeExamples/Tokyo/en/LastOSError_(Delphi)
SysUtils
(以及所有需要它的内容)时,我会得到错误代码50
(请求不受支持
)。但是@Jonathan是正确的,除非实际发生了错误,否则没有理由调用GetLastError
。想象一下,在完全不同的窗口中发生了10分钟前的错误。然后,出于某种原因,您调用GetLastError
,从而返回来自10分钟前的相同代码。 - Jerry DodgeExtractShortPathName
不是Windows API调用,而是内置于Delphi SysUtils中的函数,其又调用了GetShortPathName
API :) - Jerry Dodge