自定义异常是扩展的任何类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