代码之家  ›  专栏  ›  技术社区  ›  bohdan_trotsenko

如何忽略f中的异常#

  •  5
  • bohdan_trotsenko  · 技术社区  · 15 年前

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

    如果我意识到这一点,只是想忽略它我如何在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中,异常不会被忽略。

    2 回复  |  直到 15 年前
        1
  •  8
  •   Brian    15 年前

    Try with和Try Finally是f_中的独立结构,因此需要额外的“Try”来匹配finally:

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

    正如维塔利指出的那样,将“使用”用于处理

    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

        2
  •  5
  •   Vitaliy Liptchinsky    15 年前

    在f_中不支持Try..With..Finally。以及在OCAML中。 你应该使用 使用 此处声明:

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