Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Situations Require Throw/Catch In Elixir?

Tags:

elixir

So a conversation arose for me and some friends around a passage in this page of Elixir documentation.

In Elixir, a value can be thrown and later be caught. throw and catch are reserved for situations where it is not possible to retrieve a value unless by using throw and catch.

Those situations are quite uncommon in practice except when interfacing with libraries that do not provide a proper API.

Which situations would require using try/throw/catch vs. try/rescue? Is this for interfacing with some existing Erlang libraries? The sample on the page shows Elixir code which is what I find a bit confusing.

What would be the "proper API" that I should be looking for? I mean would this be a protocol?

like image 839
Onorio Catenacci Avatar asked Mar 16 '16 13:03

Onorio Catenacci


1 Answers

I consider raise/rescue to be explicitly about exception handling - meaning completely unexpected situation where you want to have a stacktrace and a programmer looking at it. It may happen because of multiple things - programmer error, wrong environment, etc, but user providing invalid data is not one of those cases.

Throw/catch is useful in places where you have expected failures, but you still want to use the non-local control flow that is offered by raise/rescue. This also allows you to skip the cost of building a stacktrace that is sometimes considerable. Classic examples are:

  • exiting a deeply nested recursive call: https://github.com/devinus/poison/blob/master/lib/poison/parser.ex#L34-L46
  • normal error handling is too expensive (can occur in too many places): https://github.com/michalmuskala/mongodb_ecto/blob/master/lib/mongo_ecto/objectid.ex#L29-L43
  • you have an non-local construct (like transactions): https://github.com/elixir-lang/ecto/blob/428126157b1970d10f9d5233397f07c35ce69cac/test/support/test_repo.exs#L84-L98

My rule of thumb for choice of one over the other would be that catch is essential to properly functioning program while rescue should be removable in the general case. Of course there are exceptions to that rule, but I think it's a useful first-level distinction.

like image 181
michalmuskala Avatar answered Sep 21 '22 16:09

michalmuskala