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
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法