5.8. Declaring That a Method Can Throw an Exception
Problem
You want to declare that a method can throw an exception, either to alert callers to this fact or because your method will be called from Java code.
Solution
Use the @throws annotation to
declare the exception(s) that can be thrown. To declare that one
exception can be thrown, place the annotation just before the method
signature:
@throws(classOf[Exception])overridedefplay{// exception throwing code here ...}
To indicate that a method can throw multiple exceptions, list them all before the method signature:
@throws(classOf[IOException])@throws(classOf[LineUnavailableException])@throws(classOf[UnsupportedAudioFileException])defplaySoundFileWithJavaAudio{// exception throwing code here ...}
Discussion
The two examples shown are from an open source project I created that lets developers play WAV, AIFF, MP3, and other types of sound files. I declared that these two methods can throw exceptions for two reasons. First, whether the consumers are using Scala or Java, if they’re writing robust code, they’ll want to know that something failed.
Second, if they’re using Java, the @throws annotation is the Scala way of
providing the throws method signature
to Java consumers. It’s equivalent to declaring that a method throws an
exception with this Java syntax:
publicvoidplay()throwsFooException{// code here ...}
It’s important to note that Scala’s philosophy regarding checked exceptions is different than Java’s. Scala doesn’t ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access