exception-handling - 如何忽略 F# 中的异常

标签 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()
}

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

最佳答案

try-with 和 try-finally 在 F# 中是单独的构造,因此您需要额外的“尝试”来匹配 finally:

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

正如 Vitaliy 指出的那样,将“use”用于 finally-that-dispose 更为惯用
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

关于exception-handling - 如何忽略 F# 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789682/

相关文章:

python引发错误异常

c# - 当这么多事情都可能出错时,你所做的就是尝试,尝试,尝试

f# - FSharp.Data.TypeProviders SQLDataConnection

f# - 与 MailboxProcessor 和 Task 的交互永远挂起

c# - 创建一个我希望处理的自定义异常是个好主意吗?

java - 处理java异常的最佳实践

java - Eclipse 不认为 System.exit 会中断执行

f# - F# 中的动态编程

asp.net-core - 如何在 saturn 应用程序中访问和使用用户 secret

.net - 在 F# 中正确使用带有指针的 P/invoke