我正在编写只能捕获特定类型异常的函数。
def myFunc[A <: Exception]() {
try {
println("Hello world") // or something else
} catch {
case a: A => // warning: abstract type pattern A is unchecked since it is eliminated by erasure
}
}
在这种情况下绕过 jvm 类型删除的正确方法是什么?
最佳答案
您可以像 this answer 中那样使用 ClassTag
.
但我更喜欢这种方法:
def myFunc(recover: PartialFunction[Throwable, Unit]): Unit = {
try {
println("Hello world") // or something else
} catch {
recover
}
}
用法:
myFunc{ case _: MyException => }
使用ClassTag
:
import scala.reflect.{ClassTag, classTag}
def myFunc[A <: Exception: ClassTag](): Unit = {
try {
println("Hello world") // or something else
} catch {
case a if classTag[A].runtimeClass.isInstance(a) =>
}
}
另请注意,通常您应该将 Try
与 recover
方法一起使用:Try
只会捕获 NonFatal
异常(exception)。
def myFunc(recover: PartialFunction[Throwable, Unit]) = {
Try {
println("Hello world") // or something else
} recover {
recover
}.get // you could drop .get here to return `Try[Unit]`
}
关于Scala:抽象类型模式 A 未被选中,因为它已被删除消除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21180973/