Scala finally塊

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...