Home Developer Why use Try instead of Scala Try Catch

Why use Try instead of Scala Try Catch

Author

Date

Category

Scala try catch is always an option when writing Scala code for Java like exception control flows.
However, you also have the option of start using the Try type.

Scala try catch vs Try

Try was introduced in Scala 2.10 and behaves as a mappable Either without having to select right or left.

In the example below, taken from the Scala API:

def divide: Try[Int] = {  
  val dividend = Try(Console.readLine("Enter an Int that you'd like to divide:n").toInt)
  val divisor = Try(Console.readLine("Enter an Int that you'd like to divide by:n").toInt)
  val problem = dividend.flatMap(x => divisor.map(y => x/y))
  problem match {
    case Success(v) =>
      println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v)
      Success(v)
    case Failure(e) =>
      println("You must've divided by zero or entered something that's not an Int. Try again!")
      println("Info from the exception: " + e.getMessage)
      divide
  }
}

You can see how, instead of using explicit try and catch to treat exceptions, Try is used to encapsulate the operation which is always an instance of either Success or Failure.

Benefits

You get, according again to the official documentation the:

[..] ability to pipeline, or chain, operations, catching exceptions along the way. You can map as you would a collection, an option or a right projection of an Either.

Furthermore, they encode exceptions in the Type system allowing for better documentation and clearer intention.
The Effective Scala[2] guide states:

using Option or com.twitter.util.Try are good, idiomatic choices, as they harness the type system to ensure that the user is properly considering error handling.

Start enforcing it today withย Codacy

Login to your account and enable the pattern โ€œEnforce usage of the Try objectโ€ to enforce it in your projects

1: Scala API http://www.scala-lang.org/api/current/index.html#scala.util.Try
2: Effective Scala http://twitter.github.io/effectivescala

Learn more about Scala

Check out other Scala resources on our blog.


Edit: We just published an ebook: โ€œThe Ultimate Guide to Code Reviewโ€ based on a survey of 680+ developers. Enjoy!

About Codacy

Codacy is used by thousands of developers to analyze billions of lines of code every day!

Getting started is easy โ€“ and free! Just use yourย ย GitHub, Bitbucket or Google account toย sign up.

GET STARTED

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our newsletter

To be updated with all the latest news, offers and special announcements.

Recent posts

How does code quality fit into your CI/CD pipeline?

Continuous Integration and Continuous Deployment (CI/CD) are key for organizations wanting to deliver software at scale. CI/CD allows developers to automate...

How Stim uses Codacy to achieve high-quality code

We spoke with Tobias Sjรถsten, Head of Software Engineering at Stim, about how Codacy helps them guarantee code quality and standardization...

6 things developers should do to ship more secure code

Writing better, more secure source code is fundamental to prevent potential exploits and attacks that could undermine your software applications. However,...

Best practices for security code reviews

In today's interconnected world, where data breaches and cyber threats are increasingly common, one of your top priorities should be to...

April Product Update ๐Ÿš€

Hi there ๐Ÿ‘‹ It's been a whirlwind month, and we have big news to share: