我正在学习Ruby并遇到了fail关键字.这是什么意思?
if password.length < 8
fail "Password too short"
end
unless username
fail "No user name set"
end
Run Code Online (Sandbox Code Playgroud)
cra*_*bob 128
在Ruby中,fail是同义词raise.该fail关键字是所述的方法Kernel,其是由类包括模块Object.该fail方法像raise关键字一样引发运行时错误.
该fail方法有三个重载:
fail:引发一个RuntimeError没有错误消息.
fail(string):RuntimeError使用字符串参数引发a 作为错误消息:
fail "Failed to open file"
Run Code Online (Sandbox Code Playgroud)fail(exception [, string [, array]]):exception使用可选的错误消息(第二个参数)和回调信息(第三个参数)引发类(第一个参数)的异常.
示例:假设您定义了一个在给定错误参数时应该失败的函数.提高一个ArgumentError而不是一个是更好的RuntimeError:
fail ArgumentError, "Illegal String"
Run Code Online (Sandbox Code Playgroud)
另一个示例:您可以将整个回溯传递给fail方法,以便可以访问rescue块内的跟踪:
fail ArgumentError, "Illegal String", caller
Run Code Online (Sandbox Code Playgroud)
caller是一个Kernel方法,它将backtrace作为表单中的字符串数组返回file:line: in 'method'.
没有参数,在$中引发异常!或者如果$,则引发RuntimeError!没有.使用单个String参数,将字符串作为消息引发RuntimeError.否则,第一个参数应该是Exception类的名称(或者在发送异常消息时返回Exception对象的对象).可选的第二个参数设置与异常关联的消息,第三个参数是回调信息的数组.开始...结束块的救援条款捕获了例外情况.
来源:内核模块上的Ruby文档.
kub*_*oon 28
Rubocop说两个词的用法;
"使用
fail而不是raise发出异常信号.""使用
raise而不是fail重新抛出异常."
这是一个例子.
def sample
fail 'something wrong' unless success?
rescue => e
logger.error e
raise
end
Run Code Online (Sandbox Code Playgroud)
Bor*_*cky 27
fail == raise
换句话说,fail它只是raise提升错误方法的流行别名.用法:
fail ArgumentError, "Don't argue with me!"
Run Code Online (Sandbox Code Playgroud)
www.ruby-doc.org是你的朋友.当我用谷歌搜索rubydoc fail" 内核 "是第一次打击.我的建议是,如果有疑问,请找到这样定义的东西的权威来源.