17.2. Add Exception Annotations to Scala Methods to Work with Java
Problem
You want to let Java users know that a method can throw one or
more exceptions so they can handle those exceptions with
try
/catch
blocks.
Solution
Add the @throws
annotation to
your Scala methods so Java consumers will know which methods can throw
exceptions and what exceptions they throw.
For example, the following Scala code shows how to add an @throws
annotation to let callers know that
the exceptionThrower
method can throw
an Exception
:
// scala
class
Thrower
{
@throws
(
classOf
[
Exception
])
def
exceptionThrower
{
throw
new
Exception
(
"Exception!"
)
}
}
With your Scala method annotated like that, it will work just like
a Java method that throws an exception. If you attempt to call exceptionThrower
from a Java class without
wrapping it in a try
/catch
block,
or declaring that your Java method throws an exception, the compiler (or
your IDE) will give you the following error:
unreported exception java.lang.Exception; must be caught or declared to be thrown
In your Java code, you’ll write a
try
/catch
block as usual to handle
the exception:
// java
Thrower
t
=
new
Thrower
();
try
{
t
.
exceptionThrower
();
}
catch
(
Exception
e
)
{
System
.
err
.
println
(
"Caught the exception."
);
e
.
printStackTrace
();
}
If you want to declare that your Scala method throws multiple exceptions, add an annotation for each exception:
@throws
(
classOf
[
IOException
])
@throws
(
classOf
[
LineUnavailableException
])
@throws
(
classOf
[
UnsupportedAudioFileException
])
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.