[英]How to catch an exception and throw a different exception
I have a for loop that I'm expecting an IndexOutOfBoundsException
on. 我有一个for循环,希望在其中打开IndexOutOfBoundsException
。 I want this particular exception, when raised, to throw a custom exception. 我希望在引发此特定异常时抛出自定义异常。 I currently have this: 我目前有这个:
try {
for (i <- 0 until end) {
// do something
}
} catch {
case e: IndexOutOfBoundsException =>
throw CustomException("Raised expected IndexOutOfBoundsException", e)
}
However, when the above snippet is run, the compiler tells me that an IndexOutOfBoundsException
was raised and not my custom exception. 但是,当运行以上代码片段时,编译器告诉我引发了IndexOutOfBoundsException
而不是我的自定义异常。 What would I have to do to raise my custom exception? 我应该怎么做才能引发自定义例外?
The custom exception is defined as: 自定义例外定义为:
case class CustomException(private val message: String = "", private val cause: Throwable = None.orNull) extends Exception(message, cause)
Use Try
and recoverWith
. 使用Try
和recoverWith
。 recoverWith
handles the failure case and further tries to propagate the success or failure of new Try computation. 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.