tags:

views:

640

answers:

2

I simply want my method call to suppress all "NoMethodError" exceptions that might arise in the methods it in turn calls.

def foo
  begin
    bar1
    bar2
  rescue Exception
    return '--'
  end
end

But this doesn't work. NoMethodError keeps being raised to the top level.

The exact error is undefined method []' for nil:NilClass' (NoMethodError)

+4  A: 
class Object
    def method_missing(meth,*args)
        # do whatever you want here
        end
    end

If you want something less global, you can do this on an narrower class, or even a specific instance:

class << my_object
    # and so forth
MarkusQ
A: 

Your code as given works fine.

Extrapolating from your error, I'm guessing what you're actual code is is more like this:

class MyClass
  def [](arg)
    self.bim
    self.bam
    self.boom
  rescue Exception
    "--"
  end
end

And that later you're trying:

obj[ 'whatever' ]

And getting undefined method []' for nil:NilClass' (NoMethodError). This isn't happening b/c you've defined the MyClass#[] method incorrectly, it's b/c your obj isn't an instance of MyClass, it's nil. Probably as a result of an earlier call.

rampion