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

不羁岁月 提交于 2019-12-10 03:34:20

问题


Scala doesn't have checked exceptions. However, when calling scala code from java, it's desirable to catch exceptions thrown by scala.

Scala:

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

Java:

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

javac doesn't like this, and complains that "this exception is never thrown from the try statement body"

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


回答1:


Use a throws annotation:

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

You can also annotate a class constructor:

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

This is covered in the Tour of Scala




回答2:


You can still catch too many exceptions and then re-throw the ones you can't handle:

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


来源:https://stackoverflow.com/questions/20006823/catch-in-java-a-exception-thrown-in-scala-unreachable-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!