个性化阅读
专注于IT技术分析

Scala finally块的用法示例

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...
赞(0)
未经允许不得转载:srcmini » Scala finally块的用法示例

评论 抢沙发

评论前必须登录!