問題是你是否真的需要try/finally
。大多數時間try/finally
用於處理資源,即使發生異常。但是你總是可以用use
關鍵字替換它。
例如:
open System.IO
let openFile(url: string) =
let fileStream = File.OpenText(url)
try
try
let readline = fileStream.ReadLine()
printfn "Readline: %s" readline
with
| :? IOException as ex ->
printfn "IOException: %A" ex
| ex -> printfn "Another exception: %A" ex
finally
fileStream.Dispose()
可以被改寫爲:
let openFile(url: string) =
use fileStream = File.OpenText(url)
try
let readline = fileStream.ReadLine()
printfn "Readline: %s" readline
with
| :? IOException as ex ->
printfn "IOException: %A" ex
| ex -> printfn "Another exception: %A" ex
對於學習目的,則使用高次函數可以如下定義mytry
:
let mytry foo bar foobar =
try
try
foo()
with
| exn -> bar exn
finally foobar()
但上面的例子看起來不太好:
let myOpenFile(url: string) =
let fileStream = File.OpenText(url)
mytry (fun() -> let readline = fileStream.ReadLine()
printfn "Readline: %s" readline)
(fun ex -> match ex with
| :? IOException ->
printfn "IOException: %A" ex
| _ -> printfn "Another exception: %A" ex)
(fun() -> fileStream.Dispose())
來源
2012-04-03 11:19:55
pad
爲什麼,我喜歡看!我需要它的時候我已經有了非常複雜的邏輯,它不僅僅是用它來談論其他應用程序。也許我可以避免它,但嘗試/與/終於是我在那裏找到的最簡單的解決方案。 – Cynede 2012-04-03 11:33:34
是的,這取決於個人的喜好。如果我不需要太頻繁地使用它,我更喜歡明確的'try/with/finally'來'mytry'。 – pad 2012-04-03 11:37:50