ex.class应该在这里等于什么?

时间:2012-03-10 17:30:48

标签: ruby exception methods exception-handling error-handling

我正在尝试使用从this website下载的代码来学习ruby。

我现在卡住了。

  def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
    # What happens when you call a method that doesn't exist.  The
    # following begin/rescue/end code block captures the exception and
    # makes some assertions about it.
    begin
      nil.some_method_nil_doesnt_know_about
    rescue Exception => ex
      # What exception has been caught?
      assert_equal NoMethodError, ex.class

  # What message was attached to the exception?
  # (HINT: replace __ with part of the error message.)
  assert_match(/__/, ex.message)
end

我应该用部分错误信息替换__,但我没有成功。嗯,我是,因为经过几次尝试后我只是用空格替换它,因为我认为错误信息在单词之间有空格。但我怎么看错误信息是什么?

1 个答案:

答案 0 :(得分:6)

您将在此处获得NoMethodError:

>> def tst
>>   nil.an_unknown_meth
>> rescue Exception => ex
>>   puts ex.class
>>   puts ex.message
>> end
 => nil 

>> tst
NoMethodError
undefined method `an_unknown_meth' for nil:NilClass

因此NoMethodError为一个类,/undefined method .* for nil:NilClass/作为一条消息应该适合。

有关ruby-docs中NoMethodErrorgenerally on Ruby Exceptions的更多信息