所以我有一個方法,它已經有一個拋出 ExceptionA 的 try 塊。現在我需要在呼叫這個方法的地方放置另一個 try 塊,并且需要拋出一個帶有一些附加細節的例外。像這樣的東西:
method inner():
try{
//some logic
} catch {
throw new ExceptionA("exceptionA occurred")
}
method outer():
identifier = fromSomeDBCallPrivateToOuter()
try{
inner()
} catch {
// now either
// throw new Exception("Error with identifier" identifier)
// or
// append identifier to thrown error from inner()
}
有人可以提供有關如何在 Scala 中執行此操作的任何見解或建議嗎?提前致謝!
uj5u.com熱心網友回復:
您在代碼段中的內容將按書面形式作業(如果您更正語法),但需要注意的是,例外是不可變的(即使它們不是,改變它們仍然不是一個好主意),所以,而不是“ appending" 到例外,你需要創建一個新的,并將原始設定為cause.
盡管使用Trymonad 而不是“程式”try/catch塊,但在 scala 中更為慣用。像這樣的東西:
case class ExceptionB(id: String, original: ExceptionA)
extends Exception(s"Badness happened with id $id", original)
def outer(): Try[ReturnType] =
val id = getId()
Try {
inner
} recover {
case e: ExceptionA if iWannaNewException => throw new Exception(s"Id: id")
case e: ExceptionA => throw ExceptionB(id, e)
}
uj5u.com熱心網友回復:
你也可以使用Either結構。Right(value)如果函式完成沒有錯誤或Left(message)包含有關錯誤的資訊,則此結構可以回傳。您可以調整您的代碼,如下所示:
def inner(): Either[String, Int] = {
if (checkSomeStuff()) Left("Cannot assigne identifier")
else Right(doSomeStuff())
}
def outer(): Either[String, Int] = {
inner() match {
case Left(error) => {
println("There is an error: " error)
// you can also throw new Exception(s"Some info about $error") here
}
case Right(identifier) => {
println("Identifier : " identifier)
doSomeStuffWithId() // do some staff for id
}
}
}
如果您想使用例外,您需要選擇誰來處理錯誤情況(在函式中inner或outer函式中)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/476269.html
