异常处理

文章目录

下面是一段异常处理的代码:

1
2
3
4
5
6
7
try {
println("start....")
throw new RuntimeException
} catch {
case re: RuntimeException => println("this is RuntimeException")
case e: Exception => println("this is Exception")
}

scala中没有多重catch block。而是使用模式匹配来逐级匹配异常并进行处理。

看下执行结果:

1
2
start....
this is RuntimeException

还可以catch Error:

1
2
3
4
5
6
7
8
try {
println("start....")
throw new OutOfMemoryError()
} catch {
case re: RuntimeException => println("this is RuntimeException")
case e: Exception => println("this is Exception")
case error: Error => println("this is an error")
}

结果如下:

1
2
start....
this is an error

当然也可以捕捉Throwable,但是在模式匹配中使用通配符却是一个更好地选项:

1
2
3
4
5
6
7
8
9
try {
println("start....")
throw new Throwable()
} catch {
case re: RuntimeException => println("this is RuntimeException")
case e: Exception => println("this is Exception")
case error: Error => println("this is an error")
case _ => println("We catched something.")
}

执行结果:

1
2
start....
We catched something.