Scala Try, Success, Failure – Functional error handling

In this post, we will discuss the Scala’s functional error handling method using Try, Success, Failure. We know that Scala is a high-level programming language that combines both object-oriented and functional programming in one place. It runs on JVM so it can be mixed seamlessly with Java. Scala’s static types helps to identify bugs at the compile time rather than run time. The Apache Spark is written in Scala language. Apart from Spark, Apache Kafka is also written in Scala.

Scala provides multiple ways to handle exceptions like try-catch-finally , try-success-failure, option-some-none. However, Try, Success, Failure is a cleaner way to handle exceptions at run time in scala. We can get the actual error stacktrack inside the Failure block and use that appropriately. The ability of catching exception details inside failure block in try-success-failure can help us to understand the error in more detail.

Scala Try, Success, Failure – Example

Suppose, we want to create a method that takes two integer numbers. Then, it divides the first integer number by the second integer number. The code for this example using Try, Success, and Failure functional exceptional handling looks like this.

package com.sample.learning

import scala.util.{Failure, Success, Try}
object trySuccessFailureExample extends App {

  def trySuccessFailureTest(firstNumber: Int, secondNumber: Int): Unit = {
    val res = Try(firstNumber / secondNumber)
    res match {
      case Success(output) => println(s"The output is: $output")
      case Failure(e) => {
        println(s"Error occurred: ${e.getMessage}")
      }
    }
  }

  //Execute with non zero values for first and second numbers
  println("*************************************************************")
  println("Executing with params: firstNumber = 10, secondNumber = 2")
  trySuccessFailureTest(10, 2)
  println("*************************************************************")
  println()

  //Divide the first number by zero
  println("*************************************************************")
  println("Executing with params: firstNumber = 10, secondNumber = 0")
  trySuccessFailureTest(10, 0)
  println("*************************************************************")
  println()
}

Output:

Sample code output
Sample code output

We get the above output when we execute the given sample code. Now, we will discuss the sample code in detail here. The above sample code contains three blocks:

  1. Try block – We put the actual code inside this block.
  2. Success block – In this block, we get the output result in case the execution of the code is successful.
  3. Failure block – In case of any exception, we land into this block with the error details.

Above, you can see that we have put the actual code that perroms the division operation inside the Try block. Then, inside the Success block, we are using the success result to print the actual output. We can use that output variable in the Success block as per our requirement. This is the place where we get the actual result in case the code block written in Try block is executed successfully. In the Failure block, we have cached the exception and printed the error message.

Thanks for the reading. Please share your inputs in the comment section.

Rate This
[Total: 1 Average: 5]

1 thought on “Scala Try, Success, Failure – Functional error handling”

  1. Pingback: Scala Option, Some, None – Exception and Null handling - SQLRelease

Leave a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.