Scala: Another way of handling exceptions using Scala Try

A nicer way to handle a scenario where you are expecting an operation to return a value or an exception and based on result you want to perform some action.

Let’s consider a very simple example/function below:

def divide(x:Integer, y:Integer) = x/y

   
All we are doing here accepting 2 numbers as parameter to divide function and dividing them to return a result. When the parameter value of “y” is “0” we’ll get an error (divide by zero) and we want to handle that error.

There are various ways in which this can be done:
1)    Using try catch block Or,
2)    Using Try class

In this example we’ll use second method. Before look at the example, “Try” class in Scala provides a function where you can wrap a result in “Try” and it provides two methods to explicitly check whether the operation was success and “Try” has valid result or not.

Let’s have a look at the example:
val tryWrapper = Try(divide(1, 2));

tryWrapper.isSuccess match {

 case true => println("Success: " + tryWrapper.get)

 case _ => println("Error")

}


Here we are wrapping divide() function call in a Try and we are explicitly check whether the operation was successful or not using isSuccess function of Try. When the operation is successful we also want to extract the result from Try, this can be done using get()  or getOrElse() function (similar to get or getOrElse operation on Option[]).

Comments

Popular posts from this blog

AEM, FORM Submission & Handling POST requests

AEM - Query list of components and templates

AEM 6.3 - Bundle Whitelisting - Deprecation of administrative authentication

AEM as a Cloud Service (AEMaaCS) – Architecture Overview