Scala throw throws 关键字

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

 

Scala Throw示例

class ExceptionExample2{  
    def validate(age:Int)={  
        if(age<18)  
            throw new ArithmeticException("You are not eligible")  
        else println("You are eligible")  
    }  
}  

object MainObject{  
    def main(args:Array[String]){  
        var e = new ExceptionExample2()  
        e.validate(10)  

    }  
}

将上面代码保存到源文件:Demo.scala中,使用以下命令编译并执行代码 -

D:\software\scala-2.12.3\bin>scalac Demo.scala
D:\software\scala-2.12.3\bin>scala Demo.scal
java.lang.ArithmeticException: You are not eligible

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值