如何捕获循环中的异常/演员的反应?

时间:2011-04-28 16:55:39

标签: scala exception-handling actor

是否有可能在behaviour内捕获异常?放置try/catch的位置?我知道react使用异常来为不同的actor重用相同的线程,这就是为什么我不知道在哪里放try/catch。我希望自己捕获某些例外用于记录。

import scala.actors._
def behaviour: PartialFunction[Any,Unit] = {
  case x => 
    println(x)
    throw new IllegalStateException
}

val a = new Actor {
  def act {
    loop {
      react {
        behaviour
      }
    }
  }
}
a.start
a ! "Bam"

1 个答案:

答案 0 :(得分:4)

eThe Actor有一个可以覆盖的异常处理函数:

override def exceptionHandler = {
   case e: Exception =>
      println(e.getMessage())
}

每当在actor中引发通常会导致它终止的异常时,exceptionHandler部分函数就会应用于异常。


修改

使用异常过滤器:

  class ExceptionalActor extends Actor{

    def act() {
      loop {
        react {
          case "bad" => throw new NoSuchFieldException("Bad Message")
          case "impossible" => throw new Exception("Impossible Exception")
          case m => println("non-bad message " + m )
        }
      }
    }

    override def exceptionHandler = {
      case e: NoSuchFieldException => println("handled " + e.getMessage() )
    }
  }

  object Tester extends App {
    val eActr = new ExceptionalActor
    eActr start

    eActr ! "any message1"
    eActr ! "bad"
    eActr ! "any message2"
    eActr ! "impossible"
    eActr ! "any message3"
  }

产生

   non-bad message any message1
   handled Bad Message
   non-bad message any message2
   org.scratch.act.ExceptionalActor@7f5663a2: caught java.lang.Exception: Impossible Exception
   :

演员死亡。

参考:Actors in Scala