Scala教程
Scala面向对象
Scala高级

Scala Throws关键字

Scala Throws 关键字

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

Scala Throws Example

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...
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4