gpt4 book ai didi

ruby koans about_nil.rb -- 问题 fr/newbie

转载 作者:数据小太阳 更新时间:2023-10-29 07:35:02 24 4
gpt4 key购买 nike

我是编程的绝对初学者。我被 ruby​​ 所吸引并设置了 koans。该部分开始于:

def test_you_dont_get_null_pointer_errors_when_calling_methods_on_nil

请解释这一行:

rescue Exception => ex

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

最佳答案

该行指出,每当它抛出类型为 Exception 的异常时,都会拯救 begin-rescue block 中的代码。 .事实证明,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

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

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

关于ruby koans about_nil.rb -- 问题 fr/newbie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5627579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com