官术网_书友最值得收藏!

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:

  1. First, import a library to catch fatal errors as follows:
    import Control.Exception (catch, SomeException)
  2. 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)
  3. Continuing as before, define and implement main as follows:
    main :: IO ()
    main = do
  4. Define a fileName string depending on the user-provided argument, defaulting to input.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"
  5. Now apply readFile on this path, but catch any errors using the library's catch :: 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 ""
  6. The input string will be empty if there were any errors reading the file. We can now use input for any purpose using the following command:
      print $ countWords input
  7. 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 of input.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)
主站蜘蛛池模板: 淮北市| 怀集县| 江西省| 巴林左旗| 垫江县| 玛曲县| 佛学| 财经| 襄汾县| 铅山县| 桂林市| 陵川县| 遂川县| 庆阳市| 张家港市| 石首市| 新野县| 乃东县| 白水县| 娱乐| 龙陵县| 疏勒县| 黄陵县| 淄博市| 秭归县| 弋阳县| 阿拉善左旗| 福鼎市| 靖远县| 高雄市| 乐东| 醴陵市| 安庆市| 吉木萨尔县| 武宣县| 洛阳市| 外汇| 合山市| 土默特右旗| 伊宁县| 建宁县|