finally
塊用於在異常時釋放資源。資源可能是檔案,網路連線,資料庫連線等,finally
塊執行程式碼執行保證。以下程式說明了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中,使用以下命令編譯並執行程式碼 -
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...