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 兄妹拍照祝福语简短的话