Throwing Exceptions in Scala
Simply create an exception object and then you throw it with the throw
keyword, for example;
1 2 3 |
throw new ArithmeticException |
Scala try catch blocks
Scala allows us to try/catch an exception and perform pattern matching using case blocks.
Consider an example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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.
Scala finally clause
finally clause executes the code irrespective of whether the expression/program prematurely terminates or successfully executes.
Consider an example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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.
That’s all for now, it’s very similar to java programming exception handling. We will look into Scala collections in next post.