更新:似乎特定于D2007.它在D2010中工作,就像它在旧版本中工作一样.
我想返回一个退出代码,具体取决于Eception Handler块中捕获的异常类型,如:
program test; {$APPTYPE CONSOLE} uses SysUtils; var Exitcode: Integer; begin Writeln('Enter error code:'); Readln(Exitcode); try raise EExternal.Create('sdsdkfjh'); except on E:EExternal do begin Writeln(E.Classname,': ',E.Message); Halt(Exitcode); end; end; end.
不幸的是,在D2007中,从异常块调用Halt(n)总是返回退出代码1,无论你传递给Halt().
显然,因为退出Exception处理程序调用Finalize,它会清除挂起(非Abort)异常,调用SysUtils.ExceptHandler:
procedure ExceptHandler(ExceptObject: TObject; ExceptAddr: Pointer); far; begin ShowException(ExceptObject,ExceptAddr); Halt(1); // <= @#$##@#$! end;
解决方法
这会有用吗?
NeedHalt := False; try raise EExternal.Create('sdsdkfjh'); except on E:EExternal do begin Writeln(E.Classname,E.Message); NeedHalt := True; end; end; if NeedHalt then Halt(Exitcode);
或这个?
try raise EExternal.Create('sdsdkfjh'); except on E:EExternal do begin Writeln(E.Classname,E.Message); AcquireExceptionObject; Halt(Exitcode); end; end;