定义的时候首先应该给予异常的名字,然后是相应的参数。
下面是一个定义的例子
exception
WrongSecond
of
int
而要引发一个异常,你可以使用 raise 关键字,捕获异常则使用 try ... with,下面看一个示例
let primes = [ 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 in
if List.exists ( fun x -> x = currentSecond) primes then
failwith " A prime second "
else
raise (WrongSecond currentSecond)
with
| Failure msg -> printf " The error is %s " msg // 捕获默认异常
| WrongSecond x ->
printf " The current was %i, which is not prime " x
testSecond()
这里是一个简单的例子,如果是当前秒数是素数,则抛出默认的Failure异常,
否则抛出 WrongSecond 异常,并将当前秒数作为参数给他,当with捕获后,他就会输出相应的异常信息
这里我修改了原书的例子,加入了with | 的使用,可以同时对多种异常进行捕获。
接下来一个例子,我们可以使用 finally 关键字,就跟使用 C# 时一样,配合 try,可以在任何情况下
处理一些事情,比如关闭句柄,关闭文件,释放资源等。
#
light
let writeToFile() =
let file = System.IO.File.CreateText( " test.txt " ) in
try
file.WriteLine( " Hello F# users " )
finally
file.Dispose()
writeToFile()
let writeToFile() =
let file = System.IO.File.CreateText( " test.txt " ) in
try
file.WriteLine( " Hello F# users " )
finally
file.Dispose()
writeToFile()