[erlang-questions] Erlang Type specifications and throw
Kostis Sagonas
kostis@REDACTED
Tue Apr 2 10:02:57 CEST 2013
On 04/02/2013 08:22 AM, Rudolph van Graan wrote:
> Hi,
>
> I want to write a type spec for a function that throws exceptions,
> something like this:
>
>> -spec where(G :: atom()) -> pid() | throw({no_name,atom()}).
>
> I don't want to use an exit signal, because this behaviour is
> intentional and the calling process will catch this and take specific
> action. But I can't write this using the -spec syntax. The documentation
> says:
>
>> Some functions in Erlang are not meant to return; either because they
>> define servers or because they are used to throw exceptions as the
>> function below:
>> my_error(Err) -> erlang:throw({error, Err}).
>>
>> For such functions we recommend the use of the special no_return()
>> type for their "return", via a contract of the form:
>>
>> -spec my_error(term()) -> no_return().
>
> no_return() is completely the wrong thing to use and just leaving out
> the throw(…) declaration is also wrong in my eyes.
You are right that the current language of function specifications does
not allow specifying exceptions that a function may throw. This could
be done either by extending the spec syntax to include this info, i.e.
allow one to write in your example something like:
-spec where(G :: atom()) -> pid() throws {no_name,atom()}.
or by introducing a new attribute -throws(...) or even -exceptions(...)
to document the exception behavior of functions.
However, neither of these alternatives is currently implemented.
But note that when functions throw exceptions, nothing gets returned. In
this respect, the no_return() return type that the documentation
currently suggests to use is correct.
Kostis
PS. I will not comment on the general use of throw in Erlang programming
as I realize that your function(s) may be more complicated than the
simple example you show us. However, in that one, simply returning
{no_name,atom()} or simply 'no_such_process' is arguably a better
alternative.
More information about the erlang-questions
mailing list