logoalt Hacker News

throwaway81523yesterday at 9:38 PM4 repliesview on HN

Article describes try/finally as a hack to get the effect of defer, but it looks to me like it's the other way around? Try/finally is more traditional, in one form or another.


Replies

wannabe44today at 4:11 AM

A (lexically-scoped) defer is a more general than a finally block. You can express finally-block semantics using defer.

It's also more exception-safe when you have more than one throwing call in the try block.

Rohansiyesterday at 10:10 PM

It's also necessary here because TypeScript has exceptions and you'd expect your `defer`s to execute even when an exception is thrown.

gtoweytoday at 2:12 AM

Finally isn't bullet proof. If you execute a promise in a try block and it happens to end without resolving, the finally block will be never be executed. Fun stuff.

show 2 replies
kaashifyesterday at 10:36 PM

If the idea of computers is that they remember stuff for you and do stuff for you, then both try/finally and defer seem like hacks to work around not having RAII like e.g. Rust or C++ where resources are closed/disposed of/deallocated automatically.

Try X finally dispose of all resources. X, defer clean up X. Or how about just X and cleanup is done automatically, with the author of the resources deciding what is needed to clean X up.

show 2 replies