我是编程中的绝对初学者。我很喜欢红宝石,并设置了koans。该部分以:
开头def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil
请解释这一行:
rescue Exception => ex
我在本节中找到了前两个公案。
答案 0 :(得分:2)
该行声明,只要它抛出类型为Exception
的异常,就会救援begin-rescue块中的代码。事实证明,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 :(得分:1)
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