finally
塊用于在異常時(shí)釋放資源。資源可能是文件,網(wǎng)絡(luò)連接,數(shù)據(jù)庫連接等,finally
塊執(zhí)行代碼運(yùn)行保證。以下程序說明了finally
塊的用法。
Scala finally塊示例
class ExceptionExample{
def divide(a:Int, b:Int) = {
try{
a/b
var arr = Array(1,2)
arr(10)
}catch{
case e: ArithmeticException => println(e)
case ex: Exception =>println(ex)
case th: Throwable=>println("found a unknown exception"+th)
}
finally{
println("Finaly block always executes")
}
println("Rest of the code is executing...")
}
}
object Demo{
def main(args:Array[String]){
var e = new ExceptionExample()
e.divide(100,10)
}
}
將上面代碼保存到源文件:Demo.scala中,使用以下命令編譯并執(zhí)行代碼 -
D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo.scal
java.lang.ArrayIndexOutOfBoundsException: 10
Finally block always executes
Rest of the code is executing...