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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With