如何在try-except语句中找出ObjFPC中的错误号

How to find out Error No. in ObjFPC in a try-except statement

我正在尝试找到一种方法来检测 objfpc 中的错误号,我尝试的方法如下所示:

Program ErrorHandling;
{$R+}
{$MODE objfpc}

Uses
SysUtils, crt;

Var
  intvar: 1 .. 100;

Begin
  Try
   clrscr;
    writeln( 'enter intvar: ');
    readln(intvar);


  Except
    on
    e: Exception
       Do
       Begin
         writeln('In Exception, IOResult: ',IOResult);
         Case IOResult Of
           201: writeln('Range intvar out of range 1-100!'); {How can we find that Error no is 201}
           Else
             writeln('Unkown Error!'); readln;
         End

       End



End;

writeln('intvar: ' , intvar);
readln;
End.

但是如果出现201 Range Error,我们如何才能找到呢?我尝试使用 IOResult 命令,但它总是显示我的 case 语句的 "Unknown Error" 字符串。

使用异常,您可以根据异常本身的类型检查错误类型。

经典的方式是:

try
    clrscr;
    writeln('enter intvar: ');
    readln(intvar);
except
    on e: ERangeError do // Executes when raised exception is ERangeError
    begin
        Writeln('Range intvar out of range 1-100!');
    end;
    on e: Exception do // Executes for any other exceptions
    begin
        Writeln(e.ClassName); // Shows exception class you can use at the "on e:" constuction
        Writeln(e.Message);
    end;
end;

看官方文档The try...except statement