建立自定義異常型別
自定義異常是任何擴充套件 Exception
或 Exception
子類的類。
一般來說,你應該總是延長 StandardError
或後代。Exception
系列通常用於虛擬機器或系統錯誤,搶救它們可以防止強制中斷按預期工作。
# Defines a new custom exception called 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
vsFileNotFoundError
DatabaseExploded
vsDatabaseExplodedError