Search code examples
exceptionscalathrow

@throws problem in Scala


I'm using Eclipse to program in Scala but it gives me an error when i use the @throws annotation.

import org.newdawn.slick.AppGameContainer
import org.newdawn.slick.BasicGame
import org.newdawn.slick.GameContainer
import org.newdawn.slick.Graphics
import org.newdawn.slick.SlickException
import scala.throws

object Base extends BasicGame("SNAKE!")
{  
  def main(args: Array[String]) 
  {
      println("Starting up")
  }

  def init(container : GameContainer)
  {
    @throws(classOf[SlickException])
  }

}

Solution

  • @throws, as you wrote, is a Scala annotation which annotates a method and explicitly declares that this method may throw an exception of the declared type (or a subclass). Annotations are meta-information on declaration. Like in Java, the annotation belongs just before the method declaration. You may want to read a bit more about Scala annotations here:

    http://www.scala-lang.org/node/106

    Now, regarding exceptions: There are no checked exception in Scala, unlike in Java, so the @throws annotation can rather be seen as documentation, whereas in Java it's required if the compiler determines that you may throw an exception that's not a RuntimeException in the body of the method.

    Finally: if you want to throw an exception in Scala, write throw new SlickException.