🎓 A1Learner
🔍
0 of 46 lessons completed

Elixir Trapping Exits

Trapping exits is a setting that turns exit notices for linked processes into ordinary messages. A process that traps exits survives a linked process ending with an error.

A linked error becomes a message

A trapping process reads the error as an EXIT message instead of ending.

Process.flag(:trap_exit, true)
child = spawn(fn -> receive do :go -> exit(:boom) end end)
Process.link(child)
send(child, :go)
receive do {:EXIT, _pid, reason} -> IO.puts(reason) end

The trapping process survives

After the EXIT message arrives, the trapping process is still alive.

Process.flag(:trap_exit, true)
child = spawn(fn -> receive do :go -> exit(:boom) end end)
Process.link(child)
send(child, :go)
receive do {:EXIT, _pid, reason} -> IO.puts(reason) end
IO.puts(Process.alive?(self()))

A normal linked end also becomes a message

A linked child ends normally, and the trapping process reads that reason too.

Process.flag(:trap_exit, true)
child = spawn(fn -> receive do :stop -> :ok end end)
Process.link(child)
send(child, :stop)
receive do {:EXIT, _pid, reason} -> IO.puts(reason) end

Example

Process.flag(:trap_exit, true)
child = spawn(fn -> receive do :go -> exit(:boom) end end)
Process.link(child)
send(child, :go)
receive do {:EXIT, _pid, reason} -> IO.puts(reason) end
child2 = spawn(fn -> receive do :stop -> :ok end end)
Process.link(child2)
send(child2, :stop)
receive do {:EXIT, _pid2, reason2} -> IO.puts(reason2) end
IO.puts(Process.alive?(self()))

Key points

  • Setting: Process.flag with trap_exit and true turns on trapping exits.
  • Message: A linked end arrives as an EXIT message carrying the reason.
  • Reason: Print only the reason from the EXIT message, not the process id.
  • Survival: A process that traps exits stays alive after a linked process ends with an error.
  • Normal: A linked process that ends normally also sends an EXIT message with the reason normal.

In this example, a trapping process links to two children in turn. The first ends with an error and the second ends normally, and the trapping process prints both reasons and stays alive.

Note

Trapping exits changes linked ends only, not plain messages.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A process traps exits and a linked process ends with an error. What does the trapping process receive?