2011-02-11 39 views
3

在下面的代碼中,我想讀取一個文件並返回所有行;如果出現IO錯誤,我希望程序退出時將錯誤消息打印到控制檯。但該程序仍然遇到未處理的異常。最佳做法是什麼? (我想我不需要Some/None,因爲我想讓程序退出,無論如何。)謝謝。F#嘗試使用未處理的異常

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

回答

4

你可以做類型測試模式匹配。

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 
+0

如果我使用printfn,如何退出程序後? – user8321

+1

@ user8321 - 當你調用'failwithf'時,你正在引發一個新的異常。當然你不想使用'printfn'? – ChaosPandion

+0

@ user8321 - 好的,如果你退出程序,打印到控制檯將是相當無意義的。 – ChaosPandion