Scala Exception Handling Example

Filed Under: Scala

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

Throwing Exceptions in Scala

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


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.


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-try-catch

Scala finally clause

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

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.

Scala-try-catch-finally

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

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages