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.
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 modulofor x <- 0..50 doz = rem(x, 11)# Exception thrown when remainder is 4if x == 4, do: throw(z)IO.puts(x)endcatch# Exception handled accordinglyx -> 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 doIO.puts("SECURITY CLEARANCE")people = {"John Krasinski", "John Cena", "John Wick"}# Iterates over people in the tuplefor x <- 0..3 doname = elem(people, x)# If the name is John Wick, then exception is thrownif name == "John Wick", do: throw(name)IO.puts("You are clear to enter: #{name}")endcatch# Exception handled accordinglyname -> 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
.
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 doexit IO.puts("exit command signaled")catch_exit, _ -> IO.puts("exit caught! handle accordingly")end
Free Resources