异常处理
F#中定义异常和定义联合类型中的constructor相似,处理异常的语法和模式匹配的语法也很相似。使用exception关键字定义异常,后面跟异常的名字。接下来是可选的关键字of。 
exception WrongSecond of int
通过raise关键字抛出异常,如下面的例子。F#除了raise关键字,还有failwith函数,如下面的例子。
#light
// define an exception type
exception WrongSecond of int
// list of prime numbers
let primes =
    [ 2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59 ]
// function to test if current second is prime
let testSecond() =
    try
        let currentSecond = System.DateTime.Now.Second in
        // test if current second is in the list of primes
        if List.exists (fun x -> x = currentSecond) primes then
        // use the failwith function to raise an exception
            failwith "A prime second"
        else
            // raise the WrongSecond exception
            raise (WrongSecond currentSecond)
        with
            // catch the wrong second exception
            WrongSecond x ->
                printf "The current was %i, which is not prime" x
    // call the function
testSecond()

 
如上面的例子,try和with关键字处理异常,with后面必须跟一个或者多个模式匹配规则。F#支持finally关键字,和try关键字一起使用。finally关键字不能和with关键字一起使用。finally表达式将会执行无论异常是否抛出。

 
#light
// function to write to a file
let writeToFile() =
// open a file
    let file = System.IO.File.CreateText("test.txt")
    try
    // write to it
    file.WriteLine("Hello F# users")
    finally
    // close the file, this will happen even if
    // an exception occurs writing to the file
    file.Dispose()
// call the function
writeToFile()