两种方式:(好吧,三种……)
(1) 干净的方式:确保在下溢条件下不违反约束。
由于显式检查,您可能会认为它很慢。但是,无论这是否算作过早优化,检查都会隐式发生以引发 Constraint_Error。这是否实际花费任何时间取决于您的编译器和优化级别。使用好的编译器可能不会。
Underflow_Error : Exception;
Declare
A,B,C : Natural;
D : Integer; -- a "bigger" type that can accommodate the worst case value
Begin
-- A := B - C; -- may raise constraint error
D := B - C;
if D < 0 then
raise Underflow_Error;
else
A := D;
end if;
End;
(2) 捕获约束错误并提高你的错误。这是不干净的,因为同一范围内的任何其他约束错误都将(误导性地)转换为下溢错误。
Underflow_Error : Exception;
Declare
A,B,C : Natural;
Begin
A := B - C; -- Let it raise constraint error
Exception:
when Constraint_Error => -- convert to my exception
raise Underflow_Error;
-- when others => raise; -- un-handled exceptions are passed upwards anyway
End;
(3) (2) 的变体捕获约束错误,执行事后分析并适当地提出。额外的计算只是在例外情况下,因此对性能基本上没有影响。
Underflow_Error : Exception;
Declare
A,B,C : Natural;
Begin
A := B - C; -- Let it raise constraint error
Exception:
when Constraint_Error => -- if appropriate, convert to my exception
if B - C < 0 then
raise Underflow_Error;
else
raise;
end if;
End;