鍍金池/ 教程/ Scala/ Scala finally塊
Scala方法重載
Scala模式匹配
Scala throw關(guān)鍵字
Scala提取器
Scala概述
Scala throws關(guān)鍵字
Scala finally塊
Scala正則表達(dá)式
Scala循環(huán)語句
Scala多線程
Scala函數(shù)
Scala final關(guān)鍵字
Scala方法覆蓋
Scala字符串
Scala線程實(shí)現(xiàn)
Scala異常處理
Scala類和對(duì)象
Scala數(shù)據(jù)類型
Scala單例和伴生對(duì)象
Scala構(gòu)造函數(shù)
Scala教程
Scala Case類和對(duì)象
Scala繼承
Scala開發(fā)環(huán)境安裝配置
Scala運(yùn)算符
Scala文件I/O
Scala線程方法
Scala變量
Scala try-catch語句
Scala基礎(chǔ)語法
Scala集合
Scala數(shù)組
Scala閉包
Scala訪問修辭符
Scala this關(guān)鍵字

Scala finally塊

finally塊用于在異常時(shí)釋放資源。資源可能是文件,網(wǎng)絡(luò)連接,數(shù)據(jù)庫連接等,finally塊執(zhí)行代碼運(yùn)行保證。以下程序說明了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中,使用以下命令編譯并執(zhí)行代碼 -

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