📜  Scala最终块

📅  最后修改于: 2021-01-09 12:00:30             🧑  作者: Mango

斯卡拉终于

finally块用于在异常期间释放资源。资源可以是文件,网络连接,数据库连接等。finally块可以保证执行。以下程序说明了finally块的用法。

Scala最终块示例

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 MainObject{
    def main(args:Array[String]){
        var e = new ExceptionExample()
        e.divide(100,10)
 
    }
}

输出:

java.lang.ArrayIndexOutOfBoundsException: 10
Finally block always executes
Rest of the code is executing...