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 婆婆高寿祝福语大全简短