The Artima Developer Community
Sponsored Link

Scala Buzz
Error handling with Scala's Try

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Rich Dougherty

Posts: 21
Nickname: richd
Registered: Aug, 2003

Rich Dougherty is a programmer from New Zealand.
Error handling with Scala's Try Posted: Jun 16, 2012 7:12 PM
Reply to this message Reply

This post originated from an RSS feed registered with Scala Buzz by Rich Dougherty.
Original Post: Error handling with Scala's Try
Feed Title: Rich Dougherty's Scala posts
Feed URL: http://blog.richdougherty.com/feeds/posts/default/-/scala?alt=rss
Feed Description: Programming with Scala.
Latest Scala Buzz Posts
Latest Scala Buzz Posts by Rich Dougherty
Latest Posts From Rich Dougherty's Scala posts

Advertisement

Scala 2.10 will introduce a new class called Try for representing the results of computations that might fail. Try neatly encodes the concept of success and failure with a subclass for each concept: Success objects hold values and Failure objects hold exceptions.

Try is a nice little utility class. It isn’t terribly exciting, but it certainly comes in handy. Its simplicity reduces confusion, and error handling is an area where confusion is common.

Of course it is not necessary to explain to the enlightened reader the danger of using special values such as -1 or null to represent errors. Programmers are famous for misusing such values and crashing their programs (and rockets). Separating success and error results into two distinct types means the compiler can make sure they’re never mixed. A bit of type checking really can help to avoid problems.

Similar type-checking assistance was available in Scala 2.9 with Either. However Either is considerably more flexible and abstract than Try. Either can represent any two possibilities, not just success and failure. Either needs a little thought to understand, whereas Try needs almost none.

Try also provides useful methods for operating on return values.

  • t.get – Get the result or throw an exception.
  • t.getOrElse(x) – Get the result or a default value.
  • t.isSuccess / t.isFailure – Check for success or failure.
  • t.map / t.flatMap – Use in a for loop and never check for failures manually again!

Scala 2.10 is going to bring lots of great stuff and it will be easy to overlook Try. But Try is a valuable addition to any programmer’s toolkit.

See also:

Read: Error handling with Scala's Try

Topic: Missing OO and FP bridge in Scala Previous Topic   Next Topic Topic: ElasticMQ 0.5: journalling, stand-alone server

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use