Ruby创建自定义异常类型
示例
自定义异常是扩展的任何类Exception或的子类Exception。
通常,您应该始终扩展StandardError或继承。该Exception系列通常是针对虚拟机或系统错误的,对其进行救援可以防止强制中断按预期工作。
#定义一个新的自定义异常,称为FileNotFound
class FileNotFound < StandardError
end
def read_file(path)
File.exist?(path) || raise(FileNotFound, "File #{path} not found")
File.read(path)
end
read_file("missing.txt") #=> raises FileNotFound.new("File `missing.txt` not found")
read_file("valid.txt") #=> reads and returns the content of the file通常通过Error在末尾添加后缀来命名异常:
ConnectionError
DontPanicError
但是,当错误不言自明时,您无需添加Error后缀,因为这将是多余的:
FileNotFound与FileNotFoundError
DatabaseExploded与DatabaseExplodedError
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短