F# try with unhandled exceptions

烈酒焚心 提交于 2019-12-23 18:07:33

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/4972436/f-try-with-unhandled-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!