You want to imagine a calculation that can either succeed or signal an error. This is an ideal use case for the monad Try .
import scala.util.{ Try, Success, Failure } def myMethod: Try[Something] = Try {
So, you return Try instead of Bool , which is infinitely more clear and idiomatic.
Usage example:
myMethod match { case Success(x) => println(s"computation succeded with result $x") case Failure(e) => println(s"computation failed with exception $e.getMessage") }
If you don't even care about the exception, but just want to return the value if successful, you can even convert Try to Option .
def myMethod: Option[Something] = Try { // do stuff // do more stuff // return something // if any exception occurs here, it gets wrapped into a Failure(e) }.toOption myMethod match { case Some(x) => println(s"computation succeded with result $x") case None => println("computation failed") }
To answer the question in the comments, you can do
Try { // do stuff } match { case Failure(_) => false case Success(_) => // do more stuff // true }
although I would suggest returning something more meaningful than Boolean when that makes sense.
Of course it can be nested.
Try { // do stuff } match { case Failure(_) => false case Success(_) => // do more stuff Try { // something that can throw } match { case Failure(_) => false case Success(_) => // do more stuff true } }
but you should consider adding Try fragments to individual functions ( Try returning).
Ultimately, we can take advantage of the fact that Try is a monad and does something like this.
Try { /* java code */ }.flatMap { _ => // do more stuff Try { /* java code */ }.flatMap { _ => // do more stuff Try { /* java code */ } } } match { case Failure(_) => false // in case any of the Try blocks has thrown an Exception case Success(_) => true // everything went smooth }