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])
}
}
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.
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.
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.
@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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With