[mercury-users] Exception handling in Mercury.
Peter Ross
pro at missioncriticalit.com
Thu Jun 28 22:02:15 AEST 2007
On 6/28/07, Bartlomiej Szymczak <rhywek at gmail.com> wrote:
> Hi, all.
>
> My mercury code uses the hash_table module. I've read the library
> reference for it, and it says:
>
> % Lookup the value associated with the given key. An
> exception is raised
> % if there is no entry for the key.
> %
> :- func lookup(hash_table(K, V), K) = V.
> :- mode lookup(hash_table_ui, in) = out is det.
>
> Guess what - indeed the exception was raised when I was testing my
> program. The program simply terminated. I've got excited, as I didn't
> know there were exceptions in Mercury.
>
> I was trying to find a way of handling this exception, but I couldn't
> find anything like "handle" in SML or "try"+"catch" in C++/Java.
>
> Is there any way of handling this exception?
>
Yes see the exception module in the standard library.
You use the predicate try or try_io which take a higher-order argument
which is the predicate you wish to evaluate and catch any exceptions
thrown by.
eg
X = 7,
exception.try(
(pred({ResultA, ResultB}::out) is det :-
( X > 10 ->
ResultA = X * 2,
ResultB = "some_string"
;
throw(X)
)
), TryResult),
(
TryResult = succeeded({A, B}),
.... do something ...
;
TryResult = exception(E),
% Handle all exceptions which are integers otherwise rethrow the exception
( dynamic_cast(E, Integer : int) ->
.. do something with the Integer ....
;
exception.throw(E)
)
> But even more useful thing for me would be raising exceptions from my
> own code. Is there such a possibility?
>
Simply call exception.throw(T)
--------------------------------------------------------------------------
mercury-users mailing list
Post messages to: mercury-users at csse.unimelb.edu.au
Administrative Queries: owner-mercury-users at csse.unimelb.edu.au
Subscriptions: mercury-users-request at csse.unimelb.edu.au
--------------------------------------------------------------------------
More information about the users
mailing list