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代码示例