Chapter3 - Exceptions And Exception Handling

异常 (Exception) 的定义跟 Union 的很相似。它是使用 exception 关键字来定义的。

定义的时候首先应该给予异常的名字,然后是相应的参数。

下面是一个定义的例子

 

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()


转载于:https://www.cnblogs.com/SinSay/archive/2010/09/29/1836440.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值