开发者

How to catch an exception within loop/react of an actor?

开发者 https://www.devze.com 2023-03-01 03:53 出处:网络
Is it possible to catch an exception raised within behaviour? Where to place the try/catch? I know that react uses exceptions to开发者_开发问答 reuse the same thread for different actors and that´s w

Is it possible to catch an exception raised within behaviour? Where to place the try/catch? I know that react uses exceptions to开发者_开发问答 reuse the same thread for different actors and that´s why I don´t know where to put the try/catch. I want to catch certain exceptions by myself for logging.

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"


eThe Actor has a exception handler function which can be overridden:

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

Whenever a exception is raised in the actor that would normally cause it to terminate - the exceptionHandler partial function is applied to the exception.


Edit

With Exception filter:

  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"
  }

produces:

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

And actor death.

ref: Actors in Scala

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号