[erlang-questions] using catch - getting error

Robert Virding rvirding@REDACTED
Sat Jun 26 00:34:09 CEST 2010


If I have understood you correctly then something like this should do
what you wish:

lk(Key, L) ->
    case lists:keysearch(Key, 1, L) of
        {value,{_,Vale}} -> Vale;
        false -> 0
    end.

lists:keysearch/3 returns whether it finds a tuple with the given key,
it does not generate an error if it does not find it. So there is no
reason to try and match it with the success return value to generate
an error if it does not find it.

Vale is flagged as unsafe as it only will get a value if
lists:keysearch succeeds and not if an error is generated so it is
unsafe to use. A variable must have a value for it to be used,
variables don't have a default value. For this reason any variable
bound within a catch will be flagged as unsafe if used after the
catch.

Robert

On 26 June 2010 00:16, Wes James <comptekki@REDACTED> wrote:
> I have this function:
>
> lk(Key, L) ->
>    {_, Error} = (catch {value, {_,Vale}} = lists:keysearch(Key, 1, L)),
>    case length(Error) of
>        0 ->
>                Val = Vale;
>        _ ->
>                Val = 0
>    end,
>    Val.
>
> A list (L) should have all the keys necessary when lk is called, but
> if the key does not exist, the keysearch will throw an exception.  I'm
> trying to catch that, but I get the error Vale is unsafe. What is the
> proper way to do this?
>
> If the key exists, then put it in Val and return Val, if the key does
> not exist, catch the error and set Val to 0.
>
> How should this be done?
>
> thx,
>
> -wes
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
>


More information about the erlang-questions mailing list