3 ms·
If setLabel() throws an exception, the scope is left, cleaning up button, which then no longer exists. The only try/catch blocks are where you can do anything u
by Fronzie 9y ago
If setLabel() throws an exception, the scope is left, cleaning up button, which then no longer exists.
The only try/catch blocks are where you can do anything usefull. That's typically only at the highest level of the application.
Exceptions depends on RAII, that's true.
- panic 9y agoThe button has to exist after leaving the scope, since the whole point is to create it and add it to the window. It can't remove itself when the function returns. You could make this general idea work, though, by adding a "button.commit();" at the end of the function. The button destructor would remove itself unless commit() had been called -- basically an ad-hoc transaction on the level of a single button.
- alkonaut 9y agoI know it's a toy example, but an exception in such a method doesn't seem like something that can be handled/retried like an IO problem. Any such exception should probably be handled by simply tearing down the app anyway.
- twic 9y agoLooking at this from a Rusty point of view, ownership rules make this possible. When this function creates but button, it owns it. To mutate it (addLabel/setAlignment/sizeToFit), it has to own it. But for it to continue to exist after the function returns, something else has to own it. Therefore, Window::addSubview has to take ownership of the button, and so, has to come last: fn make_button(window: &mut Window) { let mut button = Button::create(); button.set_label("test"); button.set_alignment(Alignment::TopLeft); button.size_to_fit(); window.add_subview(button); } (complete toy example at https://play.rust-lang.org/?gist=cb1db59a3ee1f4bad0a5472267ce8ec5&version=stable https://play.rust-lang.org/?gist=cb1db59a3ee1f4bad0a5472267c... ) In that situation, the button's destructor absolutely could delete itself.