3 ms·
It's hard to do right. RAII handles initialization fine, but error handling in the destructors is hard. Raising an exception in a destructor seldom ends well.
by Animats 12y ago
It's hard to do right. RAII handles initialization fine, but error handling in the destructors is hard. Raising an exception in a destructor seldom ends well. Go's "defer" has the same problem - what do you do if there's an error in a deferred call? Most languages with exceptions have problems in this area.
Python's "with" clause seems to be the best solution so far. The "with" clause calls __enter__ at the start and __exit__ at the end. The __exit__ gets called no matter how you leave the "with" clause. This includes exceptions and returns. Importantly, there are parameters to __exit__ which provide information about what's going on when an __exit__ is executed because of an exception. Exceptions in __exit__ can be handled and passed on, even for nested "with" clauses. Writing a proper __exit__ is a bit tricky, but that's typically done only for standard resources such as files, connections, and locks.
So nested error handling via exceptions can work well if the scoped open mechanism ("with") and the exception mechanism play well together. It took a decade to get that retrofitted into Python, but in the end, it worked well.
Rust's error types are sound, but result in rather bulky code. I've written on this before.