Stupid.Fat.Cat
Stupid.Fat.Cat

Reputation: 11285

Scala: is there a try except in scala?

In Python I can do the following:

try{
 something
}
except{
whoops that didn't work, do this instead 
}

and I'm trying to figure out if there's a way to do this very same thing in Scala. I'm seeing a lot of ways to catch exceptions, but I haven't seen a way to ignore the exception and do something else.

Edit:

So here's what I tried in Scala:

try{ 
 something
}
catch{
 case ioe: Exception => something else
}

But it doesn't seem to like it...

Upvotes: 1

Views: 4786

Answers (2)

som-snytt
som-snytt

Reputation: 39577

Some free advertising for scala.util.Try, which has additional facilities, not the least of which is that scalac will not harass you about a catch-all:

scala> try { ??? } catch { case _ => }
<console>:11: warning: This catches all Throwables. If this is really intended, use `case _ : Throwable` to clear this warning.
              try { ??? } catch { case _ => }
                                       ^

scala> import scala.util._
import scala.util._

scala> Try { ??? } map (_ => 1) recover { case _ => 0 } foreach (v => Console println s"Done with $v")
Done with 0

Upvotes: 2

om-nom-nom
om-nom-nom

Reputation: 62835

I don't see any reasons why scala's try-catch doesn't fit your needs:

scala> val foo = 0
foo: Int = 0

scala> val bar = try { 1 / foo } catch { case _: Exception => 1 / (foo + 1) } 
bar: Int = 1

Upvotes: 7

Related Questions