Catching I/O code faults
Making sure our code doesn't crash in the process of data mining or analysis is a substantially genuine concern. Some computations may take hours, if not days. Haskell gifts us with type safety and strong checks to help ensure a program will not fail, but we must also take care to double-check edge cases where faults may occur.
For instance, a program may crash ungracefully if the local file path is not found. In the previous recipe, there was a strong dependency on the existence of input.txt
in our code. If the program is unable to find the file, it will produce the following error:
mycode: input.txt: openFile: does not exist (No such file or directory)
Naturally, we should decouple the file path dependency by enabling the user to specify his/her file path as well as by not crashing in the event that the file is not found.
Consider the following revision of the source code.
How to do it…
Create a new file, name it Main.hs
, and perform the following steps:
- First, import a library to catch fatal errors as follows:
import Control.Exception (catch, SomeException)
- Next, import a library to get command-line arguments so that the file path is dynamic. We use the following line of code to do this:
import System.Environment (getArgs)
- Continuing as before, define and implement
main
as follows:main :: IO () main = do
- Define a
fileName
string depending on the user-provided argument, defaulting toinput.txt
if there is no argument. The argument is obtained by retrieving an array of strings from the library function,getArgs :: IO [String]
, as shown in the following steps:args <- getArgs let filename = case args of (a:_) -> a _ -> "input.txt"
- Now apply
readFile
on this path, but catch any errors using the library'scatch :: Exception e => IO a -> (e -> IO a) -> IO a
function. The first argument to catch is the computation to run, and the second argument is the handler to invoke if an exception is raised, as shown in the following commands:input <- catch (readFile fileName) $ \err -> print (err::SomeException) >> return ""
- The
input
string will be empty if there were any errors reading the file. We can now useinput
for any purpose using the following command:print $ countWords input
- Don't forget to define the
countWords
function as follows:countWords input = map (length.words) (lines input)
How it works…
This recipe demonstrates two ways to catch errors, listed as follows:
- Firstly, we use a case expression that pattern matches against any argument passed in. Therefore, if no arguments are passed, the
args
list is empty, and the last pattern,"_"
, is caught, resulting in a default filename ofinput.txt
. - Secondly, we use the catch function to handle an error if something goes wrong. When having trouble reading a file, we allow the code to continue running by setting
input
to an empty string.
There's more…
Conveniently, Haskell also comes with a doesFileExist :: FilePath -> IO Bool
function from the System.Directory
module. We can simplify the preceding code by modifying the input <- …
line. It can be replaced with the following snippet of code:
exists <- doesFileExist filename input <- if exists then readFile filename else return ""
In this case, the code reads the file as an input only if it exists. Do not forget to add the following import
line at the top of the source code:
import System.Directory (doesFileExist)