I previously worked a lot with Java and now I am working more with Ruby. One thing I cannot figure out though is what is the ruby equivalent to the Java "NullPointerException"? I want to test variables when I enter a function and if they are nil I want to raise this type of exception. Is there a specific ruby error class to raise this type of exception?
+5
A:
The exception list includes no such thing.
nil is an object, and items can be checked to ensure they are not nil.
result = Base.find(blah)
result.nil?
Calling a method on nil that nil (the object) doesn't have should give you a NoMethodError exception.
result = Base.find(blah) #returning no result
result.my_advanced_functionality(42)
Since result is nil, and the nil object defines no function my_advanced_functionality, you'll get a NoMethodError
One of the things I see a fair amount as I learn is "You have mistakenly called id on nil, which would be 4" (because the object id of nil is 4)
The exception heirarchy has an ArgumentError exception, which I've never used, but looks like it might serve you.
Bill D
2009-07-10 00:58:44
1-liner: raise class NullPointerException < Exception; self; end
klochner
2009-07-10 01:24:53
+6
A:
Raising an ArgumentError could suit your situation. You could do something like this:
def i_dont_take_nils_from_nobody x
raise ArgumentError.new "You gave me a nil!" if x.nil?
puts "thanks for the #{x}"
end
i_dont_take_nils_from_nobody nil
#=> ArgumentError: You gave me a nil!
i_dont_take_nils_from_nobody 1
#=> thanks for the 1
BaroqueBobcat
2009-07-10 01:58:36