如何忽略F#中的异常

时间:2009-11-24 12:12:32

标签: exception-handling f#

在正常程序执行期间,可能会发生异常。

如果我意识到它并且只想忽略它 - 我如何在F#中实现这一目标?

这是我的代码,它编译了警告:

let sha = new SHA1CryptoServiceProvider()
let maxLength = 10000
let fileSign file = 
    let fs = File.OpenRead(file)
    let mutable res = (0L, [|0uy|])
    try
        let flLen = fs.Length
        let len = int (min (int64 maxLength) flLen)

        // read 'len' bytes        
        let mutable pos = 0
        while (pos < len) do
            let chunk = fs.Read(buf, pos, len - pos)
            pos <- pos + chunk

        // get signature            
        let sign = sha.ComputeHash(buf, 0, len)

        // store new result
        res <- (flLen, sign)        
    with
        | :? IOException as e -> e |> ignore
    finally 
        if (fs <> null) then
            fs.Dispose()
    res

警告是:
error FS0010: Unexpected keyword 'finally' in binding. Expected incomplete structured construct at or before this point or other token.

我想要的相应C#等价物是:

FileStream fs = null;
try
{
    fs = File.OpenRead(file);
    // ... other stuff
}
catch
{
    // I just do not specify anything
}
finally
{ 
    if (fs != null)
        fs.Dispose()
}

如果我只省略F#中的with块,则不会忽略该异常。

2 个答案:

答案 0 :(得分:8)

try-with和try-finally是F#中的独立构造,所以你需要一个额外的'try'来匹配finally:

try
    try
        ...
    with e -> ...
finally
    ...

正如Vitaliy所指出的那样,使用'use'作为最后的东西更具惯用性 - 处置

use x = some-IDisposable-expr
...

另见

关于'使用'的文档:http://msdn.microsoft.com/en-us/library/dd233240(VS.100).aspx

“使用”规范:http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc245030850

答案 1 :(得分:5)

尝试..在F#中不支持。和OCaml一样。 您应该在此处使用使用语句:

try
   use fs = ...
with....