3 ms·
Java’s `throws` keyword comes to mind. It forces you to handle exceptions or explicitly declare that you expect the exception to be handled by a method higher
by shhsshs 4y ago
Java’s `throws` keyword comes to mind. It forces you to handle exceptions or explicitly declare that you expect the exception to be handled by a method higher up the call stack.
Your strongly-typed suggestion seems better. But you’d have to somehow allow for cases where a function opens a file, does something with it, and also expects the file to be closed by a higher function. Perhaps something like:
PleaseDeferMe<File> BeginWrite() {
PleaseDeferMe<File> p = File.open(...);
// unsafe! Make sure to return p to the calling function so this gets called with “defer” at some point
File f = unwrapDefer p;
f.Write(some header)
return p
}
- adrianmonk 4y agoYeah, or I guess you could pass some object in: File BeginWrite(DeferTrustee t) { PleaseDeferMe<File> p = File.open(...); File f = t.defer p; f.Write(some header); return f; } And then the caller would look something like: void WriteWholeFile() { DeferTrustee t = defer; // defers to the end of this function File f = BeginWrite(t); f.Write(the body); } Then you can still defer before anything else and avoid unsafe situations.