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