2017-10-18 173 views
0

我有一個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) 
+2

你可以發佈你從編譯器得到的異常嗎?我得到一個'CusomException'使用這個。 – Shaido

+0

@Shaido我得到了IndexOutOfBounds異常,而不是自定義異常。 – franklin

+1

程序是否進入代碼的catch部分?嘗試調試/打印一些東西,看看是否是這種情況。我能想到的唯一的事情就是它通常是'拋出新的CustomException',帶'new'關鍵字,但我認爲這不重要。 – Shaido

回答

0

使用TryrecoverWithrecoverWith處理失敗案例並進一步嘗試傳播新Try嘗試計算的成功或失敗。

Try { 
    for (i <- 0 until end) { 
    // do something 
    } 
}.recoverWith { case e: IndexOutOfBoundsException => 
Try.failed(CustomException("Raised expected IndexOutOfBoundsException", e)) 
}