boh*_*nko 5 f# exception-handling
在正常程序执行期间,可能会发生异常.
如果我意识到它并且只是想忽略它 - 我如何在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
Run Code Online (Sandbox Code Playgroud)
警告是:
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()
}
Run Code Online (Sandbox Code Playgroud)
如果我只是省略withF#中的块,则不会忽略该异常.
try-with和try-finally是F#中的独立构造,所以你需要一个额外的'try'来匹配finally:
try
try
...
with e -> ...
finally
...
Run Code Online (Sandbox Code Playgroud)
正如维塔利所指出的那样,使用"使用"来进行最终的处理更为惯用
use x = some-IDisposable-expr
...
Run Code Online (Sandbox Code Playgroud)
也可以看看
关于'使用'的文档: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
在F#中不支持try..with..finally.和OCaml一样.你应该在这里使用use语句:
try
use fs = ...
with....
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |