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

scala代码示例

Scala Exception handling is similar to exception handling in Java. However Scala does not support checked exceptions.

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

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

Simply create an exception object and then you throw it with the throw keyword, 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集合。

翻译自: https://www.journaldev.com/7978/scala-exception-handling-example

scala代码示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值