2011-04-11 40 views
4

我是一個絕對初學者編程。我喜歡紅寶石,並設置了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

回答

2

該行指出,只要它拋出一個類型爲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

1

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