【发布时间】:2018-03-15 12:33:26
【问题描述】:
我想try某事:
try
0/0
我不在乎它是否失败,提出Exception。但是将with 或finally 块留空会使文件无法解析。
这行得通,但写起来不好玩。
finally
null |> ignore
如何让with/finally 块(尽可能)为空?
【问题讨论】:
-
试试
(),related。
标签: f#
我想try某事:
try
0/0
我不在乎它是否失败,提出Exception。但是将with 或finally 块留空会使文件无法解析。
这行得通,但写起来不好玩。
finally
null |> ignore
如何让with/finally 块(尽可能)为空?
【问题讨论】:
(),related。
标签: f#
每个表达式都必须有结果,try ... with 也不例外。评估try 部分并获得结果。但如果try 部分失败,则替换with 部分的结果。
如果您的try 部分是0/0,那么它的结果类型是int。因此,为了匹配类型,with 部分的结果也应该是int。想一想当try部分失败时,整个表达式的结果应该是什么,并坚持下去:
let foo =
try 0/0
with _ -> 42
既然你说null |> ignore 有效,我必须得出结论,你的try 部分实际上不是0/0。 ignore 函数返回 ()(unit 类型的值),因此如果在 with 部分中这对您有用,那么您的 try 部分也必须返回 unit。如果是这种情况,您可以使用() 作为with 部分而不是null |> ignore。
let foo =
try printfn "Let's pretend that printfn may fail"
with _ -> ()
作为参考,这是(大致)ignore 的定义方式:
let ignore x = ()
【讨论】: