Java 有一个 finalize 块,它允许在一个块之后执行一些语句
离开(即使引发异常也会执行)。例子:
try {
...
} catch (Exception e) {
...
} finally {
... // any code here
}
Ada 拥有允许实现 的受控对象。敲定 手术
但是没有与 java 中相同的 finalize 块。这对记录很有用,
关闭文件、交易等(无需为每个可能的块创建特定的标记类型)。
最佳答案
正如 Adrien 在评论中提到的,Finalize
更类似于析构函数。
要获得近似异常/最终序列的东西,您可以按照这些方式做一些事情( 警告,未编译,只需输入 -- 我们将一起解决任何错误 :-) 另请参阅 Exceptions section的 Ada RM。
with Ada.Exceptions; use Ada.Exceptions;
procedure Do_Something is
-- Variables and what-not...
-- In case you have an exception and want to reraise it after you've done
-- the 'final' processing.
Exception_Caught : Exception_Occurrence := Null_Occurrence;
begin
-- You can have some statements, like initializations, here that will not
-- raise exceptions. But you don't have to, it can all just go in the
-- following block. However you want to do it...
declare
-- If you need to declare some entities local to a block, put those here.
-- If not, just omit this declare section. Be aware, though, that if
-- you initialize something in here and it raises an exception, the
-- block's exception handler will not catch it. Such an exception will
-- propagate out of the whole procedure (unless it has an outermost
-- exception handler) because you're _not_ in the block's scope yet.
begin
-- Main processing that might raise an exception
...
exception
when E : others =>
-- Handle any exception that's raised. If there are specific
-- exceptions that can be raised, they should be explicitly
-- handled prior to this catch-all 'others' one.
-- Save the exception occurrence, i.e. make a copy of it that can
-- be reraised in the 'Final' section if needed. (If you want to
-- reraise for a specific exception, do this in those handlers as
-- well.
Save_Occurrence(Exception_Caught, E);
end;
-- Final processing. Everything from here to the end of the procedure is
-- executed regardless of whether an exception was raised in the above
-- block. By it including an others handler, it ensured that no exception
-- will propagate out of this procedure without hitting this 'Final' code.
-- If an exception was raised and needs to be propagated:
if Exception_Caught /= Null_Occurrence then
Reraise_Exception(Exception_Caught);
end if;
end Do_Something;
关于ada - 在 Ada(2005 或 2012)中实现与 java finalize block 等效的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4804135/