23.4. Adnotacja throws
Adnotacja throws służy do dodawania do definicji metod informacji o wyjątkach, które mogą być wyrzucane przez te metody. Ta adnotacja ma swoją analogię w klauzuli throws z języka Java. Poniższy przykład przedstawia metodę oznaczoną dwoma adnotacjami throws.
Plik Throws1.scala: class Throws1 { @throws(classOf[Exception]) @throws(classOf[IllegalArgumentException]) def greet(greeting: String, n: Int) { if (n < 0) throw new IllegalArgumentException( "The number of repetitions must be positive.") if (n > 5) throw new Exception("Too many repetitions requested: "+n) for (j <- 1 to n) println(greeting) } }
Korzystając z mechanizmów refleksji języka Java można sprawdzić, że informacja o wyjątkach rzeczywiście została zapisana w klasie Throws1.
scala> val Some(m) = (new Throws1).getClass.getMethods.find(_.getName=="greet")
m: java.lang.reflect.Method = public void Throws1.greet(java.lang.String,int) throws java.lang.Exception,java.lang.IllegalArgumentException
scala> println(m.getExceptionTypes.mkString("\n"))
class java.lang.Exception
class java.lang.IllegalArgumentException
Plik Throws1.scala:
class Throws1 {
@throws(classOf[Exception])
@throws(classOf[IllegalArgumentException])
def greet(greeting: String, n: Int) {
if (n < 0) throw new IllegalArgumentException(
"The number of repetitions must be positive.")
if (n > 5) throw new Exception("Too many repetitions requested: "+n)
for (j <- 1 to n) println(greeting)
}
}
