O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Designing with Exceptions

If File.open succeeds, it returns {:ok, file}, where file is the service that gives you access to the file. If it fails, it returns {:error, reason}. So, for code that knows a file open might not succeed and that wants to handle the fact, you might write

 
case​ File.open(user_file_name) ​do
 
{:ok, file} ->
 
process(file)
 
{:error, message} ->
 
IO.puts :stderr, ​"Couldn't open #{user_file_name}: #{message}"
 
end

If instead you expect the file to open successfully every time, you could raise an exception on failure.

 
case​ File.open(​"config_file"​) ​do
 
{:ok, file} ->
 
process(file)
 
{:error, message} ->
 
raise​ ​"Failed to open config file: #{message}"
 
end

Or you could let Elixir raise an exception ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required