如何使用 F# 创建一个空的 catch 块?

Rya*_*ndy 0 f#

如何在 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 { }
Run Code Online (Sandbox Code Playgroud)

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

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

Tom*_*cek 5

在 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 _ ->
            ()
Run Code Online (Sandbox Code Playgroud)