虽然调用Windows API函数封装一样ExtractShortPathName
后使用GetLastError
我注意到,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
被设置,那么在我的程序开始执行之前清除该错误的正确方法是什么?我应该使用SetLastError(ERROR_SUCCESS);
这样的例子来自德尔福API文档:
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)
除非出现问题,否则不要调用GetLastError。这没有意义。 –
我有完全相同的结果。有趣的是,当我从uses子句(以及所有需要的)中删除'SysUtils'时,我得到错误代码'50'('请求不支持')。但@乔纳森的权利,没有理由调用'GetLastError',除非实际发生错误。想象一下10分钟前在完全不同的窗口中发生的错误。然后,无论出于何种原因,您调用'GetLastError',从而从10分钟前返回相同的代码。 –
API文档指出,只有在a)API调用失败时才使用GetLastError,以及b)失败的函数表示可以使用GetLastError获取有关原因的更多信息。随机地调用它或调用它而没有记录失败的功能是没有意义的。除非知道发生了错误,否则不能调用GetLastError,并且只有在您调用的特定函数指示失败后才调用GetLastError。 –