Cory Klein
Cory Klein

Reputation: 55660

Cleaner way to throw exception if unable to get return value from Try execution

A common meme I see when using Scala's wonderful Try construct is:

Try(canThrowException) match {
  case Success(result) => result
  case Failure(e) => throw new Exception("Couldn't do it", e)
}

I am often tempted to make this construct a bit more elegant:

Try(canThrowException).getOrElse(throw new Exception("Couldn't do it"))

Doing so removes my ability to chain the exception that was thrown by canThrowException, but looks prettier.

Do you know of a way to have both the elegant construct and the exception chaining?

Upvotes: 1

Views: 254

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375475

Generally it's probably better to recoverWith (and stay in Try) rather than actually throw:

val t = Try(canThrowException)

t recoverWith {
  case (e: Throwable) => { Failure(new Exception("Couldn't do it", e)) }
}

Upvotes: 1

alf
alf

Reputation: 8513

Try recover[U >: T](f: PartialFunction[Throwable, U]): Try[U]:

Try(canThrowException) recover {
  case NonFatal(e) => throw new Exception("Couldn't do it", e)
} get

The get part is ugly indeed, but given that you've just handled all the reasonable exceptions, you only have the unreasonable (and re-thrown) ones left.

Upvotes: 0

Related Questions