[英]How to catch an exception and throw a different exception
我有一個for循環,希望在其中打開IndexOutOfBoundsException
。 我希望在引發此特定異常時拋出自定義異常。 我目前有這個:
try {
for (i <- 0 until end) {
// do something
}
} catch {
case e: IndexOutOfBoundsException =>
throw CustomException("Raised expected IndexOutOfBoundsException", e)
}
但是,當運行以上代碼片段時,編譯器告訴我引發了IndexOutOfBoundsException
而不是我的自定義異常。 我應該怎么做才能引發自定義例外?
自定義例外定義為:
case class CustomException(private val message: String = "", private val cause: Throwable = None.orNull) extends Exception(message, cause)
使用Try
和recoverWith
。 recoverWith
處理失敗情況,並進一步嘗試傳播新的Try計算的成功或失敗。
Try {
for (i <- 0 until end) {
// do something
}
}.recoverWith { case e: IndexOutOfBoundsException =>
Try.failed(CustomException("Raised expected IndexOutOfBoundsException", e))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.