local f, oGuard * ... f = fopen("foo") oGuard = createobject([CFChanGuard], m.f) * from here on you can RETURN anytime if you feel like it, * without worrying about closing the file channel * ...and elsewhere
define class CFChanGuard as custom n_FChan = -1 procedure init (nFChan) this.n_FChan = m.nFChan procedure destroy if this.n_FChan <> -1 fclose(this.n_FChan) endif enddefineNow, whenever the guard object vanishes - for example, if you leave the function scope via RETURN or because of an exception - the file channel will be closed. This is especially nice during testing because you can cancel the program anytime without worrying about stuff that might get left open. I use the same approach (which is a standard idiom in C++) for restoring various settings and releasing all kinds of resources, deleting temp files ... This stuff really grows on you once you get used to it, and it greatly helps unclutter program code.