[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to make sure some operations in ANY situation? (aka: with statement in Python)
- From: "Drake Wilson" <drake@...>
- Date: Mon, 20 Jun 2011 07:53:34 -0700
On Mon, 20 Jun 2011 11:25 -0300, "Roberto Ierusalimschy" <roberto@inf.puc-rio.br> wrote:
> So, to make sure that some operations MUST happen just put them out of
> the 'if':
>
> if pcall(foo) then
> <error handling code>
> end
> <MUST happen code>
This is neat, simple, and subtly wrong (which is perhaps why other
languages have unwind-protect et al. in the first place).
function risky_operation() ... end
function handle_error(err)
local processed = gyrate_and_maybe_oom(err)
unreliable_disk_io(processed)
end
local ok, x = pcall(risky_operation)
if not ok then handle_error(x) end
-- Last call doesn't always happen!
wait_a_minute_what_about_double_faults()
So instead the translation looks more like:
local ok, x = pcall(risky_operation)
-- Eats some double faults, but often okay. Can also do
-- plain cleanup_everything() to have cleanup errors squash
-- operation errors and be propagated further, or other
-- fancier tricks...
pcall(cleanup_everything)
if not ok then handle_error(x); return end
all_righty_then(x)
---> Drake Wilson