pm100

pm100

Difference between try / rescue and try / throw

Whats the difference between the two? They seem to do identical things but one is doced as ‘only use very rarely’

Most Liked

josevalim

josevalim

Creator of Elixir

Semantically:

  • A throw is meant to be caught by you (typically within the same module that throws), can be any term

  • An error is when something goes wrong (typically not rescued), it is an exception in Elixir

  • An exit is when a process is crashing (typically not caught), can be any term

throws are handled by catchs, errors are handled by rescues. If I had a magic wand, exit would not be part of the language, especially because it is often mixed with the separate exit signal, but it exists in Erlang, so we have to support it, hence the catch kind, reason -> notation.

PRs to improve the docs are always welcome.

mudasobwa

mudasobwa

Creator of Cure

I would treat try/catch as a control flow (goto-like,) while try/rescue as handling an exceptional situation.

al2o3cr

al2o3cr

rescue is a shorthand, mostly. catch can do its job, but there’s more boilerplate and some of the shapes aren’t as nice:

try do
  1 + :foo
rescue
  e ->
    IO.puts "OH NO #{inspect(e)}"
end

(prints OH NO %ArithmeticError{message: "bad argument in arithmetic expression"})
versus

try do
  1 + :foo
catch
  :error, e ->
    IO.puts "OH NO #{inspect(e)}"
end

which prints OH NO :badarith

Using catch in this way also means that Erlang errors are not transformed into Elixir exceptions - note the different inspect output for the two cases.

LostKobrakai

LostKobrakai

You‘d use throw (+catch) there. It‘s the usecase it exists for in elixir. Though it‘s used sparingly and if you can replace things with normal control flow/returning that‘s usually preferred.

This is mostly considered to be a separate tool to error handling / rescue.

pm100

pm100

The documentation is really not very good.

Syntax

  • what is the syntax for ‘catch’, it is not explained anywhere. Docs have
  catch
  x -> "Got #{x}"

and (you show)

catch
  :error, e ->
    IO.puts "OH NO #{inspect(e)}"

Note that there is one thing after catch in the first one 2 in the second, what does that mean?

  • what does that ‘->’ mean, it looks like a match, is it?

  • can I have multiple catches to catch different things (like in other languages), if not how do I say ’ i want to catch x, but not y’

  • whats the syntax of rescue, is it different from catch

  • what does this mean

 rescue
  e in RuntimeError -> e

it suggests that RuntimeError is a collection of some kind. The docs for RuntimeError suggest its a single thing

  • I can have catch without try! (hidden away at the end under the description of Exit), how about rescue, how about after

Dynamics

  • does a raise propagate to a caller? All the examples just show one code block. Does it flow up the stack like exceptions in , say, c++? Or is it just propagated to the immediate caller.
  • how about throw, several times I have seen people say ‘its like a fancy goto’. This strongly suggests that it only works inside one function.
  • throw/1 docs says “A non-local return from a function”. Which makes it sound like its just a quick out for a function, and does not flow up the stack.
  • what happens if nobody catches a throw
  • what happens if I have a try/catch and somebody does a raise?
  • what happens if I have a try / rescue and somebody does a throw?
  • what happens if nobody rescues a raise

Actually I found the answers to a lot of these here Elixir - try/catch vs try/rescue? - Stack Overflow
This reveals all sorts of stuff that not in the elixir docs anywhere

Nobody has said what the difference between these two are. I don’t mean what are their use cases but, functionally what do they do different that leads to them having different use cases. There must be a difference

Where Next?

Popular in Questions Top

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement