简体   繁体   中英

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...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM