How to throw java's exception in jruby?

View: New views
2 Messages — Rating Filter:   Alert me  

How to throw java's exception in jruby?

by zane dennis :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I tried
   require 'java'
   include_class "java.io.IOException"
   raise IOException,"test",caller

It dose not work,any suggestion?Thanks a lot.

Re: How to throw java's exception in jruby?

by simon jenkins-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message


I had this problem a while ago, then it was because the ruby Kernel module doesnt like to raise java exceptions because they are not ruby exceptions.  To get around it for what I was doing i patched Kernel and added a small Java class to actually raise the exception.
I was only playing around testing Java with rspec however, so this may well not be the best way to do it in your situation. 

At this time i spoke with charles about it on irc as I was looking through the jruby source to see how difficult it would be to resolve there, he mentioned that there were thoughts of changing the exception model to be more compatable between ruby & java, i am not sure whether this is still on the cards or not.

If anyone has found a better way of doing this, I would be interested in hearing about it..

cheers

Simon

Note: this was done on jruby 1.1 from memory, still works on 1.1.2 however.

module Kernel
  class << self
   
    alias orig_raise raise
   
    def raise *args
      Java::rspecjava.extensions.kernel.RaiseJavaException.raise(args[0]) if (args.length == 1 && args[0].respond_to?(:java_object))
      orig_raise *args
    end
  end
end



package rspecjava.extensions.kernel;

public class RaiseJavaException
{
    public static void raise(Throwable t) throws Throwable
    {
        throw t;
    }
}





On Fri, Jun 13, 2008 at 4:12 AM, dennis zhuang <killme2008@...> wrote:
I tried
   require 'java'
   include_class "java.io.IOException"
   raise IOException,"test",caller

It dose not work,any suggestion?Thanks a lot.

LightInTheBox - Buy quality products at wholesale price!