Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@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])
  }

}
like image 467
TheBreadCat Avatar asked Apr 28 '11 07:04

TheBreadCat


People also ask

How do you throw an error in Scala?

In scala, throwing an exception is the same as Java. we create an exception object and then we throw it with the throw keyword: Example: Scala.

How do you catch exceptions in Scala?

It is best practice in Scala to handle exceptions using a try{...} catch{...} block, similar to how it is used in Java, except that the catch block uses pattern matching to identify and handle exceptions.

Why Scala does not have checked exception?

The case of Checked Exceptions Scala does not have checked exceptions. The compiler does not enforce exceptions to be handled. For example, the below code which is a direct translation of the above java code block compiles just fine. It will throw an error if there is no such file is present only at the run time.


1 Answers

@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.

like image 83
Jean-Philippe Pellet Avatar answered Sep 28 '22 05:09

Jean-Philippe Pellet