Scala @throws multiple exceptions
Asked Answered
S

2

7

I need to call scala code from java, so I need to tell the compiler that a certain method throws certain exceptions. This is easy to do for one exception, but I'm struggling to declare that a method throws multiple exceptions.

This doesn't work:

@throws( classOf[ ExceptionA ], classOf[ExceptionB] )

And, obviously, neither does this:

@throws( classOf[ ExceptionA , ExceptionB] )
Spada answered 12/12, 2013 at 13:21 Comment(2)
Have you tried adding multiple of the @throws annotation instead? Let me know if this works and I'll add as an answerSweeper
@Sweeper I had just tried it when I saw your comment, and it works. Please add it at as answer and I'll acceptSpada
S
10

In looking at the constructor for @throws, it takes a single Class[_] argument. Taking that into consideration, you won't be able to use the array notation to represent multiple classes. So the alternative it to add the annotation multiple times, one for each supported exception:

@throws( classOf[ExceptionA] )
@throws( classOf[ExceptionB] )
Sweeper answered 12/12, 2013 at 13:28 Comment(0)
L
4

@throws is defined as follow:

class throws[T <: Throwable](cause: String = "") extends scala.annotation.StaticAnnotation {...}

So you can only put one exception per annotation. Add one annotation per exception.

Lumisterol answered 12/12, 2013 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.