What is try catch in Elixir?

svg viewer

What is exception handling?

Exception handling is one of the most significant parts of a good program. A decent program should be able to recognize and eliminate possible errors and exceptions. When these possible exceptions are dealt with, the developed application becomes smoother and gives the user a better experience. No one likes a program that crashes when it runs into an unexpected value.

Luckily, like some other languages, Elixir provides ways to deal with a gracefully thrown exception. One way is to use the try/catch method.

There are two cases that are usually handled using try/catch:

  • throw
  • exit

throw

When writing a program, the programmer might want to stop the execution at a particular value. The program can throw this value whenever it is detected and then catch it to take necessary action.

Code

In this example, the programmer is running a loop through 0 to 50 and throws an exception when the remainder is equal to 4.

try do
# For loop to generate to calculate modulo
for x <- 0..50 do
z = rem(x, 11)
# Exception thrown when remainder is 4
if x == 4, do: throw(z)
IO.puts(x)
end
catch
# Exception handled accordingly
x -> IO.puts("Caught: #{x}")
end

The following example shows a basic code that checks if the input string matches the pre-set string, then an exception is thrown.

try do
IO.puts("SECURITY CLEARANCE")
people = {"John Krasinski", "John Cena", "John Wick"}
# Iterates over people in the tuple
for x <- 0..3 do
name = elem(people, x)
# If the name is John Wick, then exception is thrown
if name == "John Wick", do: throw(name)
IO.puts("You are clear to enter: #{name}")
end
catch
# Exception handled accordingly
name -> IO.puts("You are not clear to enter: #{name}")
end

exit

In Elixir code environment, processes running inside communicate by sending signals to one another. One of these signals is the exit signal, which can be naturally generated when the program dies or explicitly generated by the programmer. These explicitly generated exit signals are handled accordingly with throw/catch.

Code

To explicitly generate an exit signal, write exit. Then, as soon as the exit signal is generated, instead of shutting down the program, the exception can be handled in the catch block.

try do
exit IO.puts("exit command signaled")
catch
_exit, _ -> IO.puts("exit caught! handle accordingly")
end

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved