1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > scala代码示例_Scala异常处理示例

scala代码示例_Scala异常处理示例

时间:2023-03-04 00:39:08

相关推荐

scala代码示例_Scala异常处理示例

scala代码示例

Scala Exception handlingis similar to exception handling in Java. HoweverScaladoes not supportchecked exceptions.

Scala异常处理类似于Java中的异常处理 。 但是,Scala不支持检查的异常

Scala中的抛出异常 (Throwing Exceptions in Scala)

Simply create an exception object and then you throw it with thethrowkeyword, for example;

只需创建一个异常对象,然后使用throw关键字将其throw;例如,

throw new ArithmeticException

Scala尝试捕获块 (Scala try catch blocks)

Scala allows us to try/catch an exception and perform pattern matching using case blocks.

Scala允许我们尝试/捕获异常并使用case块执行模式匹配。

Consider an example below.

考虑下面的示例。

object Arithmetic {def main(args: Array[String]) {try {val z = 4/0} catch {case ex: ArithmeticException => {println("Cannot divide a number by zero")}}}}

Here we are trying to divide a number by zero and catch the arithmetic exception in the catch block. The case Arithmetic exception is matched and the statement “Cannot divide a number by zero” is printed.

在这里,我们尝试将数字除以零,然后在catch块中捕获算术异常。 匹配算术异常的情况,并打印“不能将数字除以零”的语句。

Scala的finally子句 (Scala finally clause)

finally clause executes the code irrespective of whether the expression/program prematurely terminates or successfully executes.

无论表达式/程序是否提前终止或成功执行,finally子句都将执行代码。

Consider an example below.

考虑下面的示例。

object Arithmetic {def main(args: Array[String]) {try {val z = 4/0} catch {case ex: ArithmeticException => {println("Cannot divide a number by zero")}}finally {println("This is final block")}}}

Save the code in Arithmetic.scala file and run as shown in below image.

将代码保存在Arithmetic.scala文件中,然后如下图所示运行。

That’s all for now, it’s very similar to java programming exception handling. We will look into Scala collections in next post.

到此为止,这与Java编程异常处理非常相似。 我们将在下一篇文章中研究Scala集合。

翻译自: /7978/scala-exception-handling-example

scala代码示例

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。