开发者

Throwing Java exception in JRuby and catching it in Java

开发者 https://www.devze.com 2023-04-12 22:01 出处:网络
I have created my own UI component in Java. It has model and a few of model\'s methods can throw my exception called ModelException. I want to use this component in JRuby but I can\'t raise my ModelEx

I have created my own UI component in Java. It has model and a few of model's methods can throw my exception called ModelException. I want to use this component in JRuby but I can't raise my ModelException:

raise ModelException # it cause TypeError: exception class/object expected

So I tried to create method throwing ModelException in Java and then invoke it in JRuby:

public class ScriptUtils {

private ScriptUtils() {
}

public static void throwModelException(ModelException e)
        throws ModelException {
    throw e;
}
}

but when I call throwModelException from JRuby I get:

org.jruby.exceptions.RaiseException: Native Exception: 'class  app.ui.ModelException';   Message:
;开发者_StackOverflow StackTrace: app.ui.ModelException
...
Caused by: app.ui.ModelException

this native exception cannot be handled by Java code.

Any ideas how to throw Java exception in JRuby and catch it in Java?


This is a complete re-write of my original answer as I originally mis-read your question!

You can raise Java exceptions and catch them in JRuby but you need to be a bit careful how you call raise:

raise ModelException

Will cause a type error (as you saw) because to JRuby ModelException looks like a plain constant. Remember that in Ruby class names are constants. You can raise direct subclasses of Ruby Exception like this, e.g.:

raise RuntimeError

But I think such subclasses are a special case. Those that are actually Java classes you need to call with a constructor:

raise ModelException.new

Or whatever constructor/s you have for that class. An instance of ModelException, in JRuby, is a subclass of Exception because JRuby creates it as such, but the Java class itself isn't. All this is assuming that you have imported your ModelException class correctly.

As for your second example, I couldn't replicate that error at all. As long as I created the exception object correctly, as above, it worked and I didn't see any complaints about "Native Exception" at all. So I'm not sure what is happening there, sorry.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号