[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: Jerome Vuarand <jerome.vuarand@...>
- Date: Mon, 20 Jun 2011 17:48:14 +0200
2011/6/20 Xavier Wang <weasley.wx@gmail.com>:
>
> 在 2011-6-20 晚上11:30,"steve donovan" <steve.j.donovan@gmail.com>写道:
>
>>
>> 2011/6/20 Xavier Wang <weasley.wx@gmail.com>:
>> > But I have some things to do even if I want throw the error, I want to
>> > execute some code when the function I called have error, even if I don't
>> > care what error it does , I just want some resource to be clean .
>>
>> Ah, like this?
>>
>> local ok, err = pcall(problem_function)
>> if not ok then
>> pcall(cleanup)
>> error(err)
>> end
>>
>> That is, re-raise the error.
>>
>> steve d.
>>
> Yes , it's great :)
> And next question, your code cannot handle multiple return value, is there
> any more generic way to handle more situations? Just like:
>
> local ok, rets... = pcall(func)
> pcall(cleanup())
> if not ok then
> pcall(err_func)
> error(rets...)
> end
> -- using rets, note that before here I don't actually know how many values
> the function returns
> local a,b,c = rets...
Put the result in a table, and unpack it later:
local function pack(...) return {n=select('#', ...), ...} end
local rets = pack(pcall(func))
pcall(cleanup())
if not rets[1] then
pcall(err_func)
error(unpack(rets, 2, rets.n))
end
local a,b,c = unpack(rets, 2, rets.n)
...