在scala中,可以创建自己的异常。它也称为自定义异常。通过扩展Exception
类,同时声明自定义异常类。在自定义类中创建自己的异常消息。下面我们来看一个例子。
Scala Throws示例
class InvalidAgeException(s:String) extends Exception(s){}
class ExceptionExample{
@throws(classOf[InvalidAgeException])
def validate(age:Int){
if(age<18){
throw new InvalidAgeException("Not eligible")
}else{
println("You are eligible")
}
}
}
object Demo{
def main(args:Array[String]){
var e = new ExceptionExample()
try{
e.validate(5)
}catch{
case e : Exception => println("Exception Occured : "+e)
}
}
}
将上面代码保存到源文件:Demo.scala中,使用以下命令编译并执行代码 -
D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo.scal
Exception Occured : InvalidAgeException: Not eligible