Scala Exception Handling Example

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;

Scala try catch blocks

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

Consider an example below.

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-450x258

Scala finally clause

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

Consider an example below.

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

Scala-try-catch-450

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

By admin

Leave a Reply

%d bloggers like this: