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
分享到:
没有账号? 忘记密码?