Delphi 柏林 10.1 除以零异常缺失
Delphi Berlin 10.1 Division by zero exception missing
令我感到惊讶的是,除以零异常没有出现。我如何找回它?
Berlin 10.1 最近安装,新项目,
procedure TForm1.Button1Click(Sender: TObject);
var
a: Double;
begin
a := 5/0; // No exception
ShowMessage(a.ToString); // -> 'INF'
end;
您可以使用数学单元中的 SetExceptionMask 函数控制触发哪些浮点异常:http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.Math.SetExceptionMask
要禁用所有浮点异常,请使用:
SetExceptionMask(exAllArithmeticExceptions);
要启用所有浮点异常,请使用:
SetExceptionMask([]);
另请注意,在您的示例代码中,编译器将在编译时确定该值(因为表达式是常量),因此无论传递给 SetExceptionMask 的值如何,它都不会触发异常。要触发异常,您需要一个稍微复杂一点的示例,如下所示:
program test;
uses Math;
var
xx,yy: double;
begin
SetExceptionMask([]);
xx := 1;
yy := 0;
halt(round(xx/yy));
end.
a := 5/0;
表达式 5/0
在技术语言术语中是 constant expression。
A constant expression is an expression that the compiler can evaluate without executing the program in which it occurs. Constant expressions include numerals; character strings; true constants; values of enumerated types; the special constants True, False, and nil; and expressions built exclusively from these elements with operators, typecasts, and set constructors.
因此,此表达式由编译器求值,而不是在运行时求值。所以它的评估是由编译时规则决定的,不受运行时浮点单元异常掩码的影响。
那些规则规定正值除以零等于 +INF
,一个特殊的 IEEE754 值。如果您将表达式更改为至少有一个不是常量表达式的参数,那么它将在运行时进行计算,并引发除以零的异常。
令我感到惊讶的是,除以零异常没有出现。我如何找回它?
Berlin 10.1 最近安装,新项目,
procedure TForm1.Button1Click(Sender: TObject);
var
a: Double;
begin
a := 5/0; // No exception
ShowMessage(a.ToString); // -> 'INF'
end;
您可以使用数学单元中的 SetExceptionMask 函数控制触发哪些浮点异常:http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.Math.SetExceptionMask
要禁用所有浮点异常,请使用:
SetExceptionMask(exAllArithmeticExceptions);
要启用所有浮点异常,请使用:
SetExceptionMask([]);
另请注意,在您的示例代码中,编译器将在编译时确定该值(因为表达式是常量),因此无论传递给 SetExceptionMask 的值如何,它都不会触发异常。要触发异常,您需要一个稍微复杂一点的示例,如下所示:
program test;
uses Math;
var
xx,yy: double;
begin
SetExceptionMask([]);
xx := 1;
yy := 0;
halt(round(xx/yy));
end.
a := 5/0;
表达式 5/0
在技术语言术语中是 constant expression。
A constant expression is an expression that the compiler can evaluate without executing the program in which it occurs. Constant expressions include numerals; character strings; true constants; values of enumerated types; the special constants True, False, and nil; and expressions built exclusively from these elements with operators, typecasts, and set constructors.
因此,此表达式由编译器求值,而不是在运行时求值。所以它的评估是由编译时规则决定的,不受运行时浮点单元异常掩码的影响。
那些规则规定正值除以零等于 +INF
,一个特殊的 IEEE754 值。如果您将表达式更改为至少有一个不是常量表达式的参数,那么它将在运行时进行计算,并引发除以零的异常。