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 except开发者_Python百科ion. 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
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
精彩评论