Scala的异常处理和Java类似,也是try{}catch{}finally{},不同的是,Scala中没有checked exception,所有异常在catch代码块用模式匹配处理,示例如下:
scala> import java.io.FileReader
import java.io.FileReader
scala> import java.io.FileNotFoundException
import java.io.FileNotFoundException
scala> import java.io.IOException
import java.io.IOException
scala>
scala> object Test {
| def main(args: Array[String]) {
| try {
| val f = new FileReader("input.txt")
| } catch {
| case ex: FileNotFoundException => {
| println("Missing file exception")
| }
| case ex: IOException => {
| println("IO Exception")
| }
| } finally {
| println("Exiting finally...")
| }
| }
| }
defined object Test
scala> Test.main(Array("Test"))
Missing file exception
Exiting finally...
(代码来自:)
参考:
阅读(1049) | 评论(0) | 转发(0) |