Facebook Twitter LinkedIn E-mail
magnify
Home F# F#开发教程(12):函数化编程(十一)
formats

F#开发教程(12):函数化编程(十一)

Published on 2016 年 08 月 28 日

异常和异常处理

F#中定义异常和定义联合类似,异常处理类似于模式匹配。定义异常使用excpetion关键字,然后是异常的名称,再次为可选的异常数据类型。多个类型使用*分隔(其实是元组类型)
例如

exception WrongSecond of int

使用raise来抛出异常。F#中还有一个failwith函数可以抛出异常。

> exception WrongSecond of int
- let primes = [ 2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59 ];;

exception WrongSecond of int
val primes : int list =
  [2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59]

> let testSecond() =
-     try
-         let currentSecond = System.DateTime.Now.Second 
-         if List.exists (fun x -> x = currentSecond) primes then
-             failwith "A prime second"
-         else
-             raise (WrongSecond currentSecond)
-     with
-     WrongSecond x ->
-         printf "The current was %i,which is not prime" x;;

val testSecond : unit -> unit

> testSecond();;
The current was 1,which is not primeval it : unit = ()

try 和 with 用来处理异常,将可能会出现异常的表达式放在try 和 with 之间。with之后定义一个或多个异常类型的模式匹配。和普通的模式匹配最大的差异在于异常的模式匹配在没有没有完全定义所有异常模式处理时编译器不会给出警告,这是因为任何没有处理的异常都会逐步向上传播。
F#也支持finally,它和try一起使用。但finally不能和with一同使用。

// 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()
 
Tags:
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn