24

特定の型の例外のみをキャッチできる関数を書いています。

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 タイプの消去をバイパスする正しい方法は何ですか?

4

2 に答える 2

28

この回答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 recovermethod:を使用する必要があることにも注意してください。例外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]`
}
于 2014-01-17T08:41:42.973 に答える