lua-users home
lua-l archive

Re: How to make sure some operations in ANY situation? (aka: with statement in Python)

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 2011年6月20日 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

AltStyle によって変換されたページ (->オリジナル) /