Ken*_*ter 3 delphi error-handling winapi delphi-xe8
GetLastError在调用Windows API函数包装器之后使用,就像ExtractShortPathName我注意到的那样GetLastError,无论调用ExtractShortPathName成功还是失败,都会返回非零错误代码.事实上,在我的程序执行之前似乎存在"最后一个错误",例如
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.
Run Code Online (Sandbox Code Playgroud)
结果是:
EOSError: System Error. Code: 122.
The data area passed to a system call is too small
Run Code Online (Sandbox Code Playgroud)
我误解了什么或做错了什么?
如果Delphi运行时正在执行某些导致GetLastError设置的操作,那么在程序开始执行之前清除该错误的正确方法是什么?我应该SetLastError(ERROR_SUCCESS);像Delphi 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;
Run Code Online (Sandbox Code Playgroud)
http://docwiki.embarcadero.com/CodeExamples/Tokyo/en/LastOSError_(Delphi)
Nat*_*Nat 13
返回的值GetLastError()仅在失败的Windows API调用之后立即相关,并且该函数的文档指定通过调用可获得扩展错误信息GetLastError().
在该上下文之外调用它将返回先前调用的内容,该调用可以来自您的代码,Delphi运行时,您调用的DLL,甚至是Windows API中的某些内容......
作为状态的Windows API文档GetLastError():
当函数的返回值指示此类调用将返回有用数据时,应立即调用GetLastError函数.
| 归档时间: |
|
| 查看次数: |
421 次 |
| 最近记录: |