Catch an exception thrown in Scala in Java - unreachable catch block

Scala has no exceptions noted. However, when calling scala code from java, it is advisable to catch the exceptions thrown by scala.

Scala:

def f()= { //do something that throws SomeException } 

Java:

 try { f() } catch (SomeException e) {} 

javac dislikes this and complains that "this exception is never thrown from the body of the try statement"

Is there a way to make scala declare that it has thrown a checked exception?

+7
java scala exception-handling scala-java-interop compiler-errors
source share
2 answers

Use the throws annotation:

 @throws(classOf[SomeException]) def f()= { //do something that throws SomeException } 

You can also annotate the class constructor :

 class MyClass @throws(classOf[SomeException]) (arg1: Int) { } 

This is covered in a Scala tour

+11
source share

You can still catch too many exceptions and then throw back those you cannot handle:

 try { f(); } catch (Exception e) { if (e instanceof SomeException) // Logic else throw e; } 
+9
source share

All Articles