F#尝试处理未处理的异常 [英] F# try with unhandled exceptions

查看:76
本文介绍了F#尝试处理未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我想读取一个文件并返回所有行;如果出现IO错误,我希望程序退出并显示错误消息到控制台.但是程序仍然会遇到未处理的异常.最佳做法是什么? (我想我不需要Some/None,因为无论如何我都想退出程序.)谢谢.

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

推荐答案

您可以键入测试模式匹配.

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

这篇关于F#尝试处理未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆