Ruby exception handling: cannot suppress NoMethodError

I just want my method call to suppress all "NoMethodError" exceptions that may occur in the methods that it calls.

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

But that does not work. NoMethodError continues to rise to the upper level.

Exact error undefined method[] 'for nil: NilClass' (NoMethodError)

+3
source share
2 answers
class Object
    def method_missing(meth,*args)
        # do whatever you want here
        end
    end

If you want something less global, you can do it in a narrower class or even in a specific instance:

class << my_object
    # and so forth
+9
source

Your code, as indicated, works great.

Extrapolating from your error, I assume that you actual code looks more like this:

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

And what later do you try:

obj[ 'whatever' ]

undefined method []' for nil:NilClass' (NoMethodError). . B/c MyClass#[], b/c obj MyClass, it nil. , .

0

Source: https://habr.com/ru/post/1705419/


All Articles