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 ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.