I'd like to use onCleanup objects (among other things) to restore the initial matlabpath if the function terminates unexpectedly.
However, there is a problem with this: the execution order of onCleanup is uncertain, and it usually restores path before the destruction of some other created custom objects. As these custom objects depend on the modified path, they can't be properly destroyed with their delete() methods after onCleanup restores the initial path. In fact, onCleanup always seems to execute before the destruction of other objects (may be because it is also created first).
May be it is possible to create one large "restore environment" function, in which the order of destruction could be enforced, like it's advised in the Tips section of the function reference page ).
However, it would be nicer for me just to be able to ensure that onCleanup objects (or better one selected onCleanup object) are destroyed last when function terminates.