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] )
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) { // ... }
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.
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.
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] )
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With