Catch in Java a exception thrown in Scala - unreac

2019-04-27 01:58发布

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?

2条回答
够拽才男人
2楼-- · 2019-04-27 02:30

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;
}
查看更多
祖国的老花朵
3楼-- · 2019-04-27 02:53

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

查看更多
登录 后发表回答