所以我在 Scala 中有一個 Try 塊
def fromString(s: String): Option[Pitch] = scala.util.Try {
val (pitchClassName, octaveName) = s.partition(c => !c.isDigit)
val octave = if octaveName.nonEmpty then octaveName.toInt else 5
Pitch(pitchClassIndex(pitchClassName) octave * 12)
} match {
case scala.util.Success(value) => Some(value)
case scala.util.Failure(e) =>
case scala.util.Failure(e) => throw e
}
現在,我知道這里有很多代碼需要解釋。對于這個問題,雖然需要知道的是:
在使用給定的音符(如“D#4”)創建 Pitch 實體時,可能有兩種不同的例外需要我專門處理。第一個是如果 Map pitchClassIndex 找不到給定的鍵 pitchClassName,第二個是如果 Pitch 引數在給定范圍之外。
音高等級索引:
val pitchClassIndex: Map[String, Int] = pitchClassNames.zipWithIndex.toMap
音高類名稱:
val pitchClassNames: Vector[String] = Vector("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")
所以現在我們輸入s: String并檢查它是否有一個數字,如果有的話把它分成元組val (pitchClassName, octaveName)如果s = "D#4"元組現在是("D#", "4")
val octave = 4那么現在在創建我們的 Pitch 實體時我們將從pitchClassIndex: Map[String, Int]鍵中獲取值pitchClassName: String = "D#"(注意這里如果 pitchClassName 不對應到 pitchClassNames 中的一個值,我們將得到一個例外)然后我們將首先添加octave: Int = 4乘以 12。Pitch(51)
現在 Pitch 的前兩行如下所示:
case class Pitch(nbr: Int):
assert((0 to 127) contains nbr, s"Error: nbr $nbr outside (0 to 127)")
因此,如果傳遞給 Pitch 的引數超出范圍,(0 to 127)則 throw 和 AssertionError 并帶有錯誤訊息。
所以現在我們有兩種情況可以拋出例外,第一種是一開始的斷言。第二個是如果pitchClassIndex(pitchClassName)使用未包含在pitchClassNames: Vector[String]例如“K#”中的鍵。然后它會拋出一個 NoSuchElementException 訊息:“找不到密鑰:K#”
現在,正如您所看到的,我在測驗 Try 陳述句的匹配運算式中有一個空的失敗案例,在這種情況下,我想檢查例外 e 是 AssertionError 還是 NoSuchElementException,如果是其中之一,我想列印一些特殊的文本。最后一種情況是針對其他例外情況。但是我不太確定如何測驗這個?有什么我可以在失敗中寫的東西,比如 (e: ???) 有什么想法嗎?
uj5u.com熱心網友回復:
您可以為兩個例外添加兩個 case 子句
case Failure(e: AssertionError) =>
// do something
case Failure(e: NoSuchElementException) =>
// do something else
case Failure(e) =>
// goes here for other exceptions
如果您想將它們組合成一個案例,您將無法再捕獲變數中的詳細資訊e,因此這可能不是一種選擇:
case Failure(_: AssertionError)
| Failure(_: NoSuchElementException) =>
// cannot use `e` anymore
我想你可以訴諸 .isInstanceOf
case Failure(e)
if e.isInstanceOf[AssertionError] ||
e.isInstanceOf[NoSuchElementException] =>
// now `e` is Throwable in here
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376841.html
