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
])
override
def
play
{
// 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
])
def
playSoundFileWithJavaAudio
{
// 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:
public
void
play
()
throws
FooException
{
// code here ...
}
It’s important to note that Scala’s philosophy regarding checked exceptions is different than Java’s. Scala doesn’t ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.