【问题标题】:What should ex.class be equal to here?ex.class 在这里应该等于什么?
【发布时间】:2012-03-27 18:16:52
【问题描述】:

我正在尝试使用从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

结束

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

【问题讨论】:

  • 正确,您的示例在我的控制台中与 NoMethodError 一起使用。那你能把错误信息贴出来吗?
  • 我认为我在发布问题时犯了一个错误,所以我更新了它。

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


【解决方案1】:

你会在这里得到一个 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 的信息

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2011-01-19
    • 1970-01-01
    • 2019-02-09
    • 2016-05-05
    相关资源
    最近更新 更多