f# - 如何使用 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# 中,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 _ ->
()
推荐阅读
- javascript - 用 vanillaJS 处理插入符号(文本插入点)
- c# - 管理 datagridview 单元格值时应用程序冻结
- java - RxJava:通过在 Observable.create() 中嵌套事件源将回调转换为反应流,而不是存储 ObservableEmmiter
- database - 具有属性总和约束的 MongoDB 查询
- javascript - 使用 API 数据在 Javascript 中翻转卡片
- c# - 使用wingdi函数(SetWorldTransform)一起缩放和旋转
- mysql - org.mule.runtime.api.connection.ConnectionException
- javascript - 如何以角度解决区域感知承诺?
- r - 如何在管道工 api 中上传 xlsx 文件作为输入
- filesystems - Openstack - 创建实例 1 或 2 天后文件系统更改为只读模式。之后无法访问任何文件