ruby​​ koans about_nil.rb - question fr/newbie

问题描述:

我是一个绝对初学者编程。我喜欢红宝石,并设置了koans。本节开始:ruby​​ koans about_nil.rb - question fr/newbie

def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil 

请解释这条线:

rescue Exception => ex 

我在本节想通了前两个koans。

+1

这就是所谓的评论 “异常处理”。尝试检查*。投票结束您的问题为“一般参考”。 – 2011-04-11 21:11:39

+0

@Pavel +1一般参考:http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html – 2011-04-11 22:59:17

该行指出,只要它抛出一个类型为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 
    puts "hi" 
rescue Exception => ex 
    puts "ERROR!" 
end 
#=> Prints "hi", and does not print ERROR! 
+1

谢谢迈克我理解你的答案的一部分与救济。约翰 – 2011-04-12 03:11:16

+1

@John,很高兴听到。 – 2011-04-12 03:14:14

你看了在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