Alex Rivera | Logout

Catching an exception within a map

Asked 2010-11-03T17:00:33.397
20

What is the best way of handling exceptions while iterating over a loop in Scala?

For instance, if I had a convert() method that could throw an exception, I'd like to catch that exception, log it, and keep iterating. Is there a "scala" way to do this?

Ideally, I'd like something like...

val points: Seq[Point] = ...
val convertedPoints: Seq[ConvertedPoint] = points.map(
   p => {
     try { p.convert() } 
     catch { case ex: Exception => logger.error("Could not convert", ex) }
})

You can't do the above code since it's not a direct mapping from one list to the other (you get back Seq[Any] as opposed to Seq[ConvertedPoint]).

Edit
Report

1 Answer

6

Perhaps you want a flatMap. Here is an example, should see how it can fit :-)

List(1,2,3,4).flatMap(x => if (x > 2) Some(x) else None)

The above would use side-effect logging (printing or putting in something mutable -- if this is done, make sure the evaluation is forced!). To get around the side-effects and caveats, the mapping function could just be of Point -> Either[CovertedPoint,Exception] and then the results can be separated with Seq.partition or similar.

answered 2010-11-03T17:04:26.053

Your Answer