2009-11-24 39 views
5

正常程序执行期间可能会发生异常。如何忽略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块,则不会忽略该异常。

回答

8

尝试,与和尝试,终于是F#中分离的构建,所以你需要一个额外的“尝试”到最后匹配:

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

由于维塔利指出的那样,这是更地道使用“使用”对于finallys - 即,处置

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

5

try..with..finally在F#中不受支持。和OCaml一样。 您应该使用使用声明在这里:

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