Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala @throws multiple exceptions

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] )
like image 841
loopbackbee Avatar asked Dec 12 '13 13:12

loopbackbee


People also ask

Can you throw multiple exceptions in one throw statement?

You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... } catch (NullPointerException npe) { // ... }

How do you handle exceptions in Scala?

IOException object Demo { def main(args: Array[String]) { try { val f = new FileReader("input. txt") } catch { case ex: FileNotFoundException => { println("Missing file exception") } case ex: IOException => { println("IO Exception") } } finally { println("Exiting finally...") } } } Save the above program in Demo.

Why Scala does not have checked exception?

The case of Checked Exceptions Scala does not have checked exceptions. The compiler does not enforce exceptions to be handled. For example, the below code which is a direct translation of the above java code block compiles just fine. It will throw an error if there is no such file is present only at the run time.


2 Answers

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] )
like image 54
cmbaxter Avatar answered Sep 19 '22 08:09

cmbaxter


@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.

like image 31
vptheron Avatar answered Sep 21 '22 08:09

vptheron