Search code examples
exceptiondestructoradatry-finallylanguage-implementation

Do Ada 83 exceptions include resource cleanup?


Ada 83 was one of the first languages to have exceptions. (I want to say 'the first', but one thing I have learned from looking into the history of technology is that there is almost always an earlier X.)

From the implementation perspective, the most complex part of implementing exceptions is their interaction with resource cleanup (destructors in C++, try-finally in Java etc.); when an exception is thrown, resource cleanup code needs to be run on exit from every dynamically nested scope on the way out.

Does Ada 83 have any resource cleanup features that are invoked in this way by exceptions? Or can the implementation just do a straight longjmp?


Solution

  • The issue is not really whether exceptions clean up resources, but whether leaving a declarative scope, such as a subprogram body or a block statement, cleans up resources allocated in that scope. The reason for leaving the scope is a secondary issue. It does not much matter whether execution leaves by reaching the "end" of the scope or by propagating an exception that was raised in the scope but not handled in the scope.

    Ada 83 has a very limited concept of "resources", but does try to clean up those resources. When a scope is left, the stack frame, with all the local variables of the scope, is removed. If the scope declares a local access type, and especially if the declaration has a Storage_Size clause, the whole "collection" of dynamically allocated objects for that access type may be removed (deallocated, freed) when the scope is left (although I think this is not a strict requirement and some compilers may not have implemented it). If the scope is the master ("owner") of some tasks, the tasks must terminate before the scope can be left (but the programmer is responsible for somehow informing the tasks that they should terminate, or for aborting the tasks).

    But for most of what today are considered "resources", such as local heap allocations with non-local access types, open locally declared files, and so on, Ada 83 does not automatically clean up such local resource allocations when the local scope is left. The normal idiom is for such scopes to have a local exception handler that cleans up the resources and then (if needed) re-raises the exception or raises another exception.