user8321
user8321

Reputation: 275

F# try with unhandled exceptions

In the following code, I want to read a file and return all lines; if there is IO error, I want the program exit with error message print to console. But the program still run into unhandled exception. What's the best practice for this? (I guess I dont need Some/None since I want to the program exit at error anyway.) thanks.

let lines = 
    try 
      IO.File.ReadAllLines("test.txt")
    with
    | ex -> failwithf " %s" ex.Message

Upvotes: 3

Views: 1375

Answers (1)

ChaosPandion
ChaosPandion

Reputation: 78262

You can do type test pattern matching.

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

Upvotes: 4

Related Questions