簡體   English   中英

Scala:除了在Scala中,還可以嘗試嗎?

[英]Scala: is there a try except in scala?

在Python中,我可以執行以下操作:

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

我正在嘗試找出是否有辦法在Scala中做同樣的事情。 我看到了很多捕獲異常的方法,但是我沒有看到忽略異常並執行其他操作的方法。

編輯:

所以這是我在Scala中嘗試過的方法:

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

但這似乎並不喜歡...

我看不出scala的try-catch不能滿足您的需求的任何原因:

scala> val foo = 0
foo: Int = 0

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

一些針對scala.util.Try免費廣告,它具有其他功能,其中最重要的一點是scalac不會騷擾您的全部產品:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM