この回答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
一般に、 with recover
method:を使用する必要があることにも注意してください。例外Try
のみをキャッチします。NonFatal
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]`
}