F#尝试处理未处理的异常
在下面的代码中,我想读取一个文件并返回所有行;如果有IO错误,我希望程序退出并将错误消息打印到控制台。但程序仍会遇到未处理的异常。这方面的最佳做法是什么?(我想我不需要F#尝试处理未处理的异常,f#,F#,在下面的代码中,我想读取一个文件并返回所有行;如果有IO错误,我希望程序退出并将错误消息打印到控制台。但程序仍会遇到未处理的异常。这方面的最佳做法是什么?(我想我不需要Some/None,因为我希望程序在出错时退出。)谢谢 您可以进行类型测试模式匹配 let lines = try IO.File.ReadAllLines("test.txt") with | :? System.IO.IOException as e -> prin
Some/None
,因为我希望程序在出错时退出。)谢谢
您可以进行类型测试模式匹配
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
如果我使用printfn,那么在@user8321之后如何退出程序?当您调用
failwithf
时,您将引发一个新的异常。确定你不想使用printfn
?@user8321-问题是如果你退出程序,打印到控制台将毫无意义。谢谢。一个小问题是e.HResult不可访问。我正在考虑将控制台重定向到日志文件。您有更好的工作流吗?@user8321-您可以在退出程序之前写入windows事件日志。(不要担心HResult属性,您只需将其替换为0即可。)
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