Scala throws關鍵字

Scala提供了throws關鍵字來聲明異常。可以使用方法定義聲明異常。 它向調用者函數提供了此方法可能引發此異常的資訊。 它有助於調用函數處理並將該代碼包含在try-catch塊中,以避免程式異常終止。在scala中,可以使用throws關鍵字或throws注釋來聲明異常。

Scala Throws示例

class ExceptionExample4{
    @throws(classOf[NumberFormatException])
    def validate()={
        "abc".toInt
    }
}

object Demo{
    def main(args:Array[String]){
        var e = new ExceptionExample4()
        try{
            e.validate()
        }catch{
            case ex : NumberFormatException => println("Exception handeled here")
        }
        println("Rest of the code executing...")
    }
}

將上面代碼保存到原始檔案:Demo.scala中,使用以下命令編譯並執行代碼 -

D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo.scal
Exception handeled here
Rest of the code executing...

上一篇: Scala throw關鍵字 下一篇: Scala多線程