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

栏目: ASP.NET · 发布时间: 9年前

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

异常和异常处理

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Tornado

Introduction to Tornado

Michael Dory、Adam Parrish、Brendan Berg / O'Reilly Media / 2012-3-28 / USD 23.99

Tornado is a scalable, non-blocking web server and web application framework written in Python. It is also light-weight to deploy, fun to write for, and incredibly powerful. Tornado was written with p......一起来看看 《Introduction to Tornado》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具