gpt4 book ai didi

ruby - begin、rescue 和 => 符号是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:04 25 4
gpt4 key购买 nike

在 Ruby koans 的第 6 个练习中,有:

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 __, ex.class

# What message was attached to the exception?
# (HINT: replace __ with part of the error message.)
assert_match(/__/, ex.message)
end
end

我不知道那里的 => 符号是什么? beginrescue 我不清楚。

最佳答案

当出现问题时,您可以“引发异常”

def do_it
# ..
raise Exception.new("something went wrong !") if something_went_wrong
end

如果 something_went_wrong 为真,这将停止程序的执行。如果您不处理异常。

要处理您使用“rescue Exception”的异常

begin
do_it
rescue Exception
puts "Something went wrong, but go on anyway"
end

如果你需要处理异常,你可以用“=>”给它一个名字

begin
do_it
rescue Exception => ex
# Now "ex" is the name of the Exception. And "ex.inspect" inspects it.
puts "Something went wrong, #{ex.inspect}, .."
end

如果你喜欢ruby koans,你可能也会喜欢rubymonk在线教程。在“Ruby Primer: Ascent”中有一节关于异常的类(class)。

关于ruby - begin、rescue 和 => 符号是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16635064/

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