首页 > 解决方案 > 如何使用 F# 制作一个空的 catch 块?

问题描述

如何在 F# 中创建一个空的 catch 块(或忽略所有异常)?

我正在编写创建 SQL Server 数据库和架构的代码。这是一个示例:

let run (ipAddress : string) (port : int) (userName : string) (password : string) =
    let mutable maxTime = 0
    let mutable succeeded = false
    while not succeeded do
        try
            if maxTime > 120 then
                failwith "Unable to initialize SQL Server database in two minutes."
            Thread.Sleep(TimeSpan.FromSeconds(5.0))
            maxTime <- maxTime + 5
            let con = new ServerConnection
                          (sprintf "%s,%i" ipAddress port, userName, password)
            let server = new Server(con)

            let db = new Database(server, "mydb")
            db.Create()

            let schema = new Schema(db, "myschema")
            schema.Create()

            succeeded <- true
        with
        // what goes here as the equivalent of: catch { }

如果我遇到数据库不可用的异常,我想忽略它并继续前进;数据库位于 Docker 容器中,因此有时启动速度很慢。

但是在 F# 中执行此操作的语法是什么?

标签: f#

解决方案


在 F# 中,try .. with ..是一个表达式,它评估它所包含的表达式之一的结果。在命令式代码中,这些分支的结果是一个unit类型的值,您可以将其写为().

因此,在您的示例中,需要返回一个单位值的with分支- 您可以使用以下内容编写它:try .. with ..

let run (ipAddress : string) (port : int) (userName : string) (password : string) =
    let mutable maxTime = 0
    let mutable succeeded = false
    while not succeeded do
        try
            // all code omitted
        with _ ->
            ()

推荐阅读