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

Scala throws关键字用法示例

点击下载

Scala提供了throws关键字来声明异常。你可以使用方法定义声明异常。它向调用方函数提供此方法可能引发此异常的信息。它有助于调用者函数处理该代码并将其封装在try-catch块中, 以避免程序异常终止。在scala中, 你可以使用throws关键字或throws注释来声明异常。

Scala抛出示例

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

object MainObject{
    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...")
    }
}

输出

Exception handeled here
Rest of the code executing...
赞(0)
未经允许不得转载:srcmini » Scala throws关键字用法示例

评论 抢沙发

评论前必须登录!