[erlang-questions] try/catch

Garrett Smith <>
Mon Jun 28 23:24:18 CEST 2010


I tend to use try...of almost exclusively. IMO, something like this is
much easier to understand (assuming I have the intent right):

{ok, Db} = connect_db(),
try pgsql:squery(Db, Sp) of
  {_,[{_,_,Res}]} -> {Sp, Res}
catch
  _ -> undefined
after
  pgsql:terminate(Db)
end.

The after body is always evaluated.

On Mon, Jun 28, 2010 at 3:08 PM, Allan Wegan <> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
>> So in a previous post, it was mentioned that a variable in a try can
>> not be used afterwards.  How is this done then?  Like this:
>>
>> do_query(Sp) ->
>>       {ok, Db} = pgsql:connect(?HOST, ?DB, ?USERNAME, ?PASSWORD),
>>       try {_,[{_,_,Res}]}=pgsql:squery(Db, Sp)
>>       catch
>>       throw:Term -> Term;
>>       exit:Reason -> {'EXIT',Reason};
>>       error:Reason -> {'EXIT',{Reason,erlang:get_stacktrace()}}
>>       end,
>>       pgsql:terminate(Db),
>>       {Sp,""}.
>>
>> I want to call squery and return a value to Res, but if there is an
>> error return nothing.  {Sp. ""} was {Sp, Res}  but doesn't work since
>> Res is in the Try.
>
> Maybe, the following is what you want:
>
> do_query(Sp) ->
>        {ok, Db} = pgsql:connect(?HOST, ?DB, ?USERNAME, ?PASSWORD),
>        Result = try
>                {_,[{_,_,Res}]} = pgsql:squery(Db, Sp),
>                {Sp, Res}
>        catch
>                _:_ -> 'undefined';
>        end,
>        pgsql:terminate(Db),
>        Result
> .
>
>
>
> - --
> Allan Wegan
> Jabber: 
> ICQ:    209459114
> Phone:  +49 40 6732962
> Schöneberger Strasse 60, 22149 Hamburg, Germany
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v2.0.12 (MingW32)
>
> iQEcBAEBAgAGBQJMKQ9dAAoJENm5axHh7AcxPMcIAL+/z/wTjIrQDSPNWaFnEBiw
> IE0JVnyQz04QfhQ9mJcpiKOdatImrTfshmAV8ocklzWgkTlp6GkYJIFdJBVdKnZC
> AbViKCviFDC01A1PMfdg8aSN9r5XYCEXHX+N1mZ4rB6Wr5Wrb10j4QLxQVZDkEZi
> KW1354BDU8bd7Llw35wtWM+Vip05hBhXTzTGO3KmreKtFBKH/y1PmKEVdetxxLeH
> bwRFU6XFfUiVHQ4uKHoDOtybi11AhzIb+ajiavDenWaXppXXEisfTlsZcUQc5Er9
> SwyMBrcylNBSYysKAUbRpK67kZMyAIS/rX10PBkV9dGYAfaKejSwYhNGfgwACLk=
> =EHrJ
> -----END PGP SIGNATURE-----
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:
>
>


More information about the erlang-questions mailing list