当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Kernel.raise用法及代码示例


本文简要介绍ruby语言中 Kernel.raise 的用法。

用法

raise
raise(string, cause: $!)
raise(exception [, string [, array]], cause: $!)
也别名为:fail

如果没有参数,则在 $! 中引发异常,或者如果 $!nil 则引发 RuntimeError 。使用单个 String 参数,引发带有字符串作为消息的 RuntimeError。否则,第一个参数应该是一个Exception 类(或另一个在发送exception 消息时返回Exception 对象的对象)。可选的第二个参数设置与异常关联的消息(可通过 Exception#message 访问),第三个参数是回调信息数组(可通过 Exception#backtrace 访问)。生成的异常(可通过 Exception#cause 访问)的 cause 会自动设置为 “current” 异常( $! ),如果有的话。可以通过 :cause 参数指定替代值,即 Exception 对象或 nil

begin...end 块的rescue 子句捕获异常。

raise "Failed to create socket"
raise ArgumentError, "No parameters", caller

相关用法


注:本文由纯净天空筛选整理自ruby-lang.org大神的英文原创作品 Kernel.raise。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。