F #

2009-11-24 6 views
5

에서 예외를 무시하는 방법 정상적인 프로그램 실행 중에 예외가 발생할 수 있습니다.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() 
} 

여기

는 경고와 함께 컴파일 내 코드입니다 F #에서 with 블록을 생략하면 예외가 무시되지 않습니다.

답변

8

시도-와 시도 - 마지막으로 F 번호에 별도의 구조는, 그래서 당신은 여분의 '시도'가 마침내 일치해야합니다

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

비탈리가 지적 하듯이, 그것은 '사용'을 사용하는 것이 더 관용적이다 대한

use x = some-IDisposable-expr 
... 

이 '사용'에 대해도

문서를 참조하십시오 finallys - 그 - 폐기 : 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 #에서 지원되지 않습니다. OCaml에서도 그렇습니다. 문을 사용하십시오.

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