2009-11-24 19 views
5

Durante l'esecuzione normale del programma può verificarsi un'eccezione.Come ignorare le eccezioni in F #

Nel caso in cui sono a conoscenza e voglio solo ignorarlo - come faccio a raggiungere questo in F #?

Ecco il mio codice, che compila con un avvertimento:

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 

L'avvertimento è:
error FS0010: Unexpected keyword 'finally' in binding. Expected incomplete structured construct at or before this point or other token.

La corrispondente C# equivalenti per quello che voglio è:

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

Se ometto il blocco with in F #, l'eccezione non viene ignorata.

risposta

8

try-con e try-finally sono costrutti separati in F #, quindi è necessario un 'try' in più per abbinare il fine:

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

Come Vitaliy sottolinea, è più idiomatica da usare 'uso' per finallys-che-smaltire

use x = some-IDisposable-expr 
... 

Vedi anche

Documenti di 'uso': http://msdn.microsoft.com/en-us/library/dd233240(VS.100).aspx

Specifiche per "uso": http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html#_Toc245030850

5

try..with..finally non è supportato in F #. Così come in OCaml. Si dovrebbe usare uso dichiarazione qui:

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