Scala Exception Handling by Code Examples

Scala Exception handling is mostly very similar with Java exception handling except catch block syntax. Here I am just trying you to explain Scala exception handling concept in brief as it is a very vast topic in itself.

Before we go into the much details, first let me highlight understand the primary points regarding exception handling in Scala,

What are Exceptions in Scala?

Exception is an explicit constructs to handle expected or unexpected failures within your Scala code. Such failures could be due to,

  • Operation failure due to mismatch in any condition (i.e. Wrong values of the parameters)
  • Operation failure due to some resource is not available or error in accessing the same (i.e. Database connection failure)
  • Operation failure due to some abnormal condition occurs in your code (i.e. any operation is doing divide by zero)

How to throw an Exception in Scala?

Throwing an exception is as simple as in Java. You create an Exception object and throw it by keyword throw.

//Some Operations
//More, Operations
throw new ExceptionObject
//This code is never executed

Scala try, catch and finally blocks

try{
    //Method for getting score
    var score = getScore()
    printScore(score)
    println("this line is not executed if exception occurs");
} catch {
  case e: Exception => println("Exception : " + e);
} finally{
    println("this line is always executed");
}

//This method throws an exception if score is negative
def printScore(score: Int) {
    if(score >= 0) 
        println ("Score is: " + score) 
    else 
        throw new IllegalArgumentException("No negative argument is accepted");
}

In above code block,

  • If score is positive than method printScore() returns value otherwise it throws an exception
  • In try block if exception occurs than expression after printScore() method call will never executed
  • The catch block is executed in-case exception is occurred in respective try block
  • At the last finally block will always get executed

Handling multiple exceptions from Scala

PrimeNumber.scala

package com.backtobazics.exceptions

object PrimeNumber {
  
  //Non Functional Method for finding prime number
  def isPrimeNumber(number: Int): Boolean = {
    var i = 2
    while (i <= number / 2) {
      if (number % i == 0) {
        return false
      }
      i += 1
    }
    true
  }
  
  //Method for checking prime numbers between 1 and 100
  def checkPrimeNumber(num: Int) = {
    try {
      if (num < 1 || num > 100)
        throw new IllegalArgumentException("Number should be between 1 and 100")
      else 
        isPrimeNumber(num)       
    } catch {
      case e: IllegalArgumentException => e.printStackTrace()
      case _ => println("Exception has occurred!")
    }
  }
  
  def main(args:Array[String]){
    println("11 is prime number : " + checkPrimeNumber(11))
    println("111 is prime number : " + checkPrimeNumber(111))
  }
}

// Output:
// 11 is prime number : true
// java.lang.IllegalArgumentException: Number should be between 1 and 100
//   at com.backtobazics.exceptions.PrimeNumber$.checkPrimeNumber(PrimeNumber.scala:21)
//   at com.backtobazics.exceptions.PrimeNumber$.main(PrimeNumber.scala:32)
//   at com.backtobazics.exceptions.PrimeNumber.main(PrimeNumber.scala)
// 111 is prime number : ()
Important rules for Scala exception handling
  • In Scala, all exceptions are unchecked exceptions (no Checked Exception like Java)
  • Exception catch block uses pattern matching to handle exceptions
  • If you have declared finally block, it will always be executed whether exception is thrown from try block or not
  • In order to handle the exception, you must have try block followed by catch and/or finally blocks
  • You can use either finally block or catch block or both along with try block
  • As mentioned in my post regarding Scala data types, throw expression has return type Nothing
References

http://www.scala-lang.org/api/current/index.html#scala.util.control.Exception$

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>