【问题标题】:ruby koans about_nil.rb -- question fr/ newbieruby koans about_nil.rb -- 问题 fr/新手
【发布时间】:2011-04-11 21:07:36
【问题描述】:

我是编程方面的绝对初学者。我很喜欢 ruby​​ 并设置了 koans。本节开头:

def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil

请解释这一行:

rescue Exception => ex

我已经弄清楚了本节的前两个公案。

【问题讨论】:

标签: ruby exception-handling


【解决方案1】:

该行指出,只要它抛出类型为Exception 的异常,就会在开始救援块中拯救代码。事实证明 Exception 是所有其他异常都继承自的顶级异常(例如语法错误、无方法错误等)。正因为如此,所有的异常都会被救出。然后它将异常实例存储在变量ex 中,您可以在其中进一步查看(例如回溯、消息等)。

I'd read this guide on Ruby Exceptions.

一个例子是这样的:

begin
    hey "hi"
rescue Exception => ex
  puts ex.message
end
#=> Prints undefined method `hey' for main:Object

但是,如果 begin 块中的代码没有出错,它就不会进入救援分支。

begin
    puts "hi"
rescue Exception => ex
  puts "ERROR!"
end
#=> Prints "hi", and does not print ERROR!

【讨论】:

  • 谢谢你,迈克,我松了一口气,我理解了你的部分答案。约翰
【解决方案2】:

你看过start of the method?的评论吗

  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
    # make 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(/undefined method/, ex.message)
    end
  end

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多