2009-11-24 12 views
5

में अपवादों को अनदेखा कैसे किया जा सकता है एक अपवाद हो सकता है।सामान्य प्रोग्राम के निष्पादन के दौरान एफ #

यदि मुझे इसके बारे में पता है और बस इसे अनदेखा करना चाहते हैं - मैं इसे एफ # में कैसे प्राप्त करूं?

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.

मैं क्या चाहते हैं के लिए इसी सी # बराबर है:

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

यहाँ मेरी कोड है, जो एक चेतावनी के साथ संकलित है अगर मैं केवल एफ 12 में with ब्लॉक को छोड़ देता हूं, तो अपवाद को अनदेखा नहीं किया जाता है।

उत्तर

8

कोशिश के साथ और कोशिश-अंत में एफ # में अलग निर्माणों कर रहे हैं, तो आप एक अतिरिक्त 'कोशिश' अंत में मैच के लिए की जरूरत है:

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 # में समर्थित नहीं है। साथ ही ओकैमल में भी। आपको का उपयोग कथन का उपयोग करना चाहिए:

try 
    use fs = ... 
with.... 
संबंधित मुद्दे