Scala 中的@throws 问题
我正在使用 Eclipse 在 Scala 中进行编程,但是当我使用 @throws
注释时,它给了我一个错误。
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])
}
}
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])
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所写,@throws 是一个 Scala 注释,它注释一个方法并显式声明该方法可能会抛出所声明类型(或子类)的异常。注释是声明的元信息。与 Java 中一样,注释位于方法声明之前。您可能想在此处阅读有关 Scala 注释的更多信息:
http://www.scala-lang。 org/node/106
现在,关于异常:与 Java 不同,Scala 中没有检查异常,因此
@throws
注释可以看作文档,而在 Java 中它是必需的如果编译器确定您可能在方法主体中抛出不是RuntimeException
的异常。最后:如果你想在 Scala 中抛出异常,请编写
throw new SlickException
。@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 aRuntimeException
in the body of the method.Finally: if you want to throw an exception in Scala, write
throw new SlickException
.