F # try with unhandled exceptions

In the following code, I want to read a file and return all lines; if there is an input / output error, I want the program to exit with printing the error message to the console. But the program still encounters an unhandled exception. What is the best practice for this? (I think I don’t need it Some/None, because I want the program to exit on error.) Thank you.

let lines = 
    try 
      IO.File.ReadAllLines("test.txt")
    with
    | ex -> failwithf " %s" ex.Message
+3
source share
1 answer

You can match the type test pattern.

let lines = 
    try 
      IO.File.ReadAllLines("test.txt")
    with
    | :? System.IO.IOException as e ->
        printfn " %s" e.Message
        // This will terminate the program
        System.Environment.Exit e.HResult
        // We have to yield control or return a string array
        Array.empty
    | ex -> failwithf " %s" ex.Message
+4
source

Source: https://habr.com/ru/post/1791557/


All Articles