Scala finally块的用法示例

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

class ExceptionExample{def divide(a:Int, b:Int) = {try{a/bvar 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) }}

【Scala finally块的用法示例】输出
java.lang.ArrayIndexOutOfBoundsException: 10Finally block always executesRest of the code is executing...

    推荐阅读