博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
F#初学笔记07
阅读量:6871 次
发布时间:2019-06-26

本文共 1522 字,大约阅读时间需要 5 分钟。

异常处理
F#中定义异常和定义联合类型中的constructor相似,处理异常的语法和模式匹配的语法也很相似。使用exception关键字定义异常,后面跟异常的名字。接下来是可选的关键字of。 
exception WrongSecond of int
通过raise关键字抛出异常,如下面的例子。F#除了raise关键字,还有failwith函数,如下面的例子。
#light// define an exception typeexception WrongSecond of int// list of prime numberslet 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 primelet 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 functiontestSecond()

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

 
#light// function to write to a filelet 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 functionwriteToFile()

 

本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/900880 ,如需转载请自行联系原作者

你可能感兴趣的文章
CentOS 6.5 自动安装镜像
查看>>
Storm与Spark Streaming比较
查看>>
我的友情链接
查看>>
Exchange Server 运维管理01:Exchange中Active Directory 有什么用?
查看>>
dhcp服务在企业中的应用
查看>>
linux系统管理之四:服务状态
查看>>
VMware View FAQ[一]
查看>>
【原创翻译】布尔值(boolean)
查看>>
三元运算式、lambda表达式、内置函数map、reduce、filter以及yield生成器
查看>>
MySQL分库分表分表后数据的查询(5th)
查看>>
iOS-点击图片放大,再次点击返回原视图 类似查看相册的功能
查看>>
JAVA -- stateless4j StateMachine 使用浅析(二)
查看>>
oracle checkpoint
查看>>
KVM虚拟化开源高可用方案(六)ISCSI ON DRBD搭建及常见故障处理
查看>>
android device related
查看>>
iOS 6 Beta3即将发布,iPhone面板谍照已经曝光
查看>>
hadoop 源码包编译
查看>>
将HTML5 Canvas的内容保存为图片
查看>>
hdu2222 Keywords Search AC自动机
查看>>
网站的架构CS和中间件
查看>>